修改 Django UserCreationForm [英] Modifying Django UserCreationForm
问题描述
我想在标准的 Django UserCreationForm 中添加更多字段,所以我继续在我的应用程序的 forms.py 文件中对其进行子类化,结果如下:
I wanted to add more fields to the standard Django UserCreationForm so I went ahead and subclassed it inside of my app's forms.py file and ended up with this:
class CustomUserCreationForm(UserCreationForm):
email = forms.EmailField(label = "Email")
first_name = forms.CharField(label = "First name")
last_name = forms.CharField(label = "Last name")
class Meta:
model = User
fields = ("first_name", "last_name", "username",)
def save(self, commit=True):
user = super(CustomUserCreationForm, self).save(commit=False)
user.first_name = first_name
user.last_name = last_name
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
然后我继续为我的用户创建了一个自定义 ModelAdmin,如下所示:
I then went ahead and created a custom ModelAdmin for my Users, which looks like this:
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
inlines = [ProfileInline,]
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
admin.site.register(Class, ClassAdmin)
但是,无论我做什么,当我进入管理页面并尝试添加新用户时,新的 CustomUserCreationForm 都不会出现.我在哪里搞砸了?
No matter what I do, however, the new CustomUserCreationForm does not show up when I go into the Admin page and try to add a new user. Where am I screwing up?
似乎没有显示该表单,但正在使用该表单.如果我尝试仅使用典型 UserCreationForm 具有的用户名和密码字段来添加新用户,我会收到一个错误,当我在我的 ModelAdmin 中删除 add_form 行时,该错误会立即消失.为什么不显示?
It seems that the form is not being displayed, but is being used. If I try to add a new user using just the username and password fields that the typical UserCreationForm has, I get an error, which promptly goes away when I remove the add_form line in my ModelAdmin. Why is it not displaying?
我的本地应用程序目录中也没有任何管理模板.会不会是这个问题?
I also do not have any admin templates in my local app directory. Could this be the issue?
推荐答案
您需要将已添加的字段添加到自定义用户管理类的 add_fieldsets 属性中.
You'll need to add the fields you've added to the add_fieldsets property of your custom user admin class.
#example:
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2')}
),
)
一位用户前几天也有类似的问题:我怎样才能让 Django 用户注册单步(而不是两步)过程强制使用电子邮件? 这也涉及创建自定义用户管理表单.
A user had a similar question the other day: How can I have Django user registration single step (instead of two step)process with email compulsory? which involved creating a custom user admin form as well.
这篇关于修改 Django UserCreationForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!