gpt4 book ai didi

python - Django 管理员更改用户密码

转载 作者:行者123 更新时间:2023-12-05 04:05:11 25 4
gpt4 key购买 nike

我是 Django 的新手。我有以下代码:

型号:

class MyUser(AbstractUser):
profile = models.OneToOneField(Profile, null=True, on_delete=models.PROTECT)

我的个人资料模型只包含一些个人字段,如全名、性别、生日等。

管理员:

class MyUserInline(admin.StackedInline):
model = MyUser
exclude = ('first_name', 'last_name', 'username', 'plan', 'password')
fieldsets = (
(_('Personal info'), {'fields': ('email',)}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)


class MyUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = MyUser

def clean_password(self):
return ""

class ProfileAdmin(admin.ModelAdmin):
inlines = (MyUserInline,)
change_user_password_template = None
form = MyUserChangeForm
change_password_form = AdminPasswordChangeForm
ordering = ('myuser__email',)

def save_model(self, request, obj, form, change):
obj.myuser.username = obj.myuser.email
obj.save()

list_display = ('full_name', 'myuser_email', 'myuser_is_staff', 'myuser_is_superuser', 'myuser_is_active')

def user_change_password(self, request, id, form_url=''):
if not self.has_change_permission(request):
raise PermissionDenied
user = self.get_object(request, unquote(id))
if user is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
'name': force_text(self.model._meta.verbose_name),
'key': escape(id),
})
if request.method == 'POST':
form = self.change_password_form(user, request.POST)
if form.is_valid():
form.save()
# rest of method

# other minor methods

我无法更改用户的密码。起初,更改密码页面根本打不开(ID 为“3/password”的配置文件不存在。可能已被删除?)

添加以下代码后,它会打开,但在按下保存按钮后,我得到 'Profile' object has no attribute 'set_password'

def get_urls(self):
return [
url(
r'^(.+)/password/$',
self.admin_site.admin_view(self.user_change_password),
name='auth_user_password_change',
),
] + super(ProfileAdmin, self).

添加以下行后,没有出现错误,点击保存按钮后应该说changed successfully,但没有。

class Profile(models.Model):
.......

def set_password(self, raw_password):
self.myuser.password = make_password(raw_password)
self.myuser._password = raw_password

最佳答案

问题解决了:

class MyAdminPasswordChangeForm(AdminPasswordChangeForm):

def save(self, commit=True):
"""
Saves the new password.
"""
password = self.cleaned_data["password1"]
self.user.myuser.set_password(password)
if commit:
self.user.myuser.save()
return self.user.myuser

class ProfileAdmin(UserAdmin):
change_password_form = MyAdminPasswordChangeForm

关于python - Django 管理员更改用户密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51462317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com