问题
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