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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With