4

I'm trying to change user admin in Django. In my project the email address, first name and last name is required. I changed my user admin as following :

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

class UserAdmin(admin.ModelAdmin):
    form = UserForm
    list_display = ('first_name','last_name','email','is_active')

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

The problem is whenever I save a user with a password, it's displayed as without hashing. I guess the problem is, I need to hash the password field with my new form. But the old form does it, so is there a way that I can extend the oldform ?

1 Answer 1

7

You can subclass the existing UserChangeForm in django.contrib.auth.forms, and customise its behaviour, rather than subclassing forms.ModelForm.

from django.contrib.auth.forms import UserChangeForm

class MyUserChangeForm(UserChangeForm):
    def __init__(self, *args, **kwargs):
        super(MyUserChangeForm, self).__init__(*args, **kwargs)
        self.fields['email'].required = True
        self.fields['first_name'].required = True
        self.fields['last_name'].required = True

class UserAdmin(admin.ModelAdmin):
    form = MyUserChangeForm

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

The above will use the default behaviour for the user password, which is to display the password hash, and link to the password change form. If you want to modify that, I would look at SetPasswordForm, to see how the password is set in the Django admin.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.