我已经覆盖了“save_model”方法来管理我管理员面板应用程序中的用户密码。我想要的是:
如何定义最后一个条件?
def save_model(self, request, obj, form, change):
if not change and (not form.cleaned_data['password']) :
password = User.objects.make_random_password()
obj.set_password(password)
elif form.cleaned_data['password'] :
obj.set_password(form.cleaned_data['password'])
else
?
super(UserAdmin, self).save_model(request, obj, form, change)
答案 0 :(得分:0)
你做这一切有点太晚了。用户创建表单甚至不允许您发布未填写字段password1
和password2
的表单。如果这些字段为空,您将永远不会使用UserAdmin.save_model()
方法。
但您可以覆盖用户创建表单的save()
方法,其中允许密码字段为空,如果字段为空则设置随机密码(如果输入则使用用户密码)
作为奖励,如果用户输入密码(密码不匹配)以及检查AUTH_PASSWORD_VALIDATORS
(除'django.contrib.auth.password_validation.MinimumLengthValidator'
以外的所有密码,此代码将保留表格验证,因为空密码字段表示0个字符)。< / p>
### admin.py
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class CustomUserCreationForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['password1'].required = False
self.fields['password2'].required = False
def _clean_form(self):
super()._clean_form()
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 != password2:
self.add_error('password2', self.error_messages['password_mismatch'])
def save(self, commit=True):
user = super().save(commit=False)
user_password = self.cleaned_data["password1"]
if not user_password:
user_password = User.objects.make_random_password()
user.set_password(user_password)
if commit:
user.save()
return user
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)