Modifying Django UserCreationForm

耗尽温柔 提交于 2019-12-30 00:38:11

问题


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

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)

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?

EDIT: 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?


回答1:


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')}
        ),
    )

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.



来源:https://stackoverflow.com/questions/6682978/modifying-django-usercreationform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!