Custom user model in django does not allow setting

2020-07-14 05:46发布

I have created a custom user model which I am successfully using within my app.

The problem is that within the Admin, on the user edit screen, I get a display of the present password hash, instead of the very useful interface for setting the password.

I am using Django 1.5b1 on Python 2.7.

How can I convince the Django admin to treat my user model the same way it treats the native User, for the sake of the admin user interface?

4条回答
▲ chillily
2楼-- · 2020-07-14 06:28

Documentation suggest that you need to register the custom model with admin and also define few methods as well so that admin interface works with custom user model.

You may also have to define built-in forms for User.

From Custom users and django.contrib.admin

You will also need to register your custom User model with the admin. If your custom User model extends AbstractUser, you can use Django's existing UserAdmin class. However, if your User model extends AbstractBaseUser, you'll need to define a custom ModelAdmin class.

查看更多
家丑人穷心不美
3楼-- · 2020-07-14 06:28

Just add this to your form:

  password = ReadOnlyPasswordHashField(
      label= ("Password"),
      help_text= ("Raw passwords are not stored, so there is no way to see "
                  "this user's password, but you can change the password "
                  "using <a href=\"password/\">this form</a>."))

Borrowed from https://stackoverflow.com/a/15630360/780262

查看更多
放荡不羁爱自由
4楼-- · 2020-07-14 06:35

At least in 1.10, I was able to do the following. Simpler than the above. I put it in admin.py:

from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from myapp.models import MyUser

class MyUserAdmin(UserAdmin):
    model = MyUser

    fieldsets = UserAdmin.fieldsets + (
            (None, {'fields': ('a_custom_field',)}),
    )

admin.site.register(MyUser, MyUserAdmin)
查看更多
孤傲高冷的网名
5楼-- · 2020-07-14 06:35

If you're extending AbstractBaseUser, you'll need two forms, a creation form, and an update form without the passwords, derived from ModelForm.

Then in the Admin form, specify separate create and update forms, along with corresponding fieldsets:

class MyUserAdmin(UserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    fieldsets = (
        (None, {'fields': ('email', 'first_name', 'last_name')}),
    )
    add_fieldsets = (
        (None, {'fields': ('email', 'password', 'password2', 'first_name', 'last_name')}),
    )

Passwords for new users will work. Do password changes in the pre-defined django form instead of in admin.

查看更多
登录 后发表回答