如果我们需要在django管理员用户中添加更多验证,请添加表格,例如输入名字和姓氏以及电子邮件必须..实现这一目标的方式是什么?
答案 0 :(得分:8)
您必须创建自己的用户表单并添加必填字段:
class UserForm(forms.ModelForm):
class Meta:
model = User
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.fields['email'].required = True
self.fields['first_name'].required = True
self.fields['last_name'].required = True
然后覆盖ModelAdmin中的表单:
class UserAdmin(admin.ModelAdmin):
form = UserForm
然后在注册您自己的用户之前取消注册普通管理员用户:
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
答案 1 :(得分:6)
这扩展了Geoffroy的答案:
from django.contrib.auth.forms import UserCreationForm
class UserForm(UserCreationForm):
class Meta:
model = User
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.fields['email'].required = True
self.fields['first_name'].required = True
self.fields['last_name'].required = True
的ModelAdmin:
from django.contrib.auth.admin import UserAdmin
class CustomUserAdmin(UserAdmin):
add_form = UserForm
add_fieldsets = (
(None, {'fields':('username','password1','password2','first_name','last_name','email'),}),)
然后按上述方式取消注册:
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
答案 2 :(得分:0)
只需编写自己的form class和tell the ModelAdmin,即可将其用作表单。