Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending user admin form in django

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 ?

like image 433
iva123 Avatar asked Oct 12 '25 12:10

iva123


1 Answers

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.

like image 120
Alasdair Avatar answered Oct 15 '25 19:10

Alasdair