Register custom user model with admin auth

孤街醉人 提交于 2021-01-21 06:22:02

问题


In a Django project, I have a custom user model that adds one extra field:

class User(AbstractUser):

    company = models.ForeignKey(Company, null=True, blank=True)

This model is defined in my app, say MyApp.models.

How can I get the new User model to show up under "Authentication and Authorization" as the original django.contrib.auth model?


回答1:


class User(AbstractUser):

    class Meta:
    app_label = 'auth'

This can solve your problem but may cause some errors when you migrate your app. The other hack is define get_app_list in your AdminSite.




回答2:


I think what you're looking for is replacing the django user model. To do this, see the answer on this post: Extending the User model with custom fields in Django. I would suggest going the extending route, but that would mean both parent and child model would have to be registered.

If you really want one single model, just set the AUTH_USER_MODEL setting to your model. This essentially replaces the default model.

In your settings.py:

AUTH_USER_MODEL = "appname.UserModelName"

For more info on replacing the user model, see https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model.




回答3:


In admin.py use

from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

UserAdmin.list_display = ('email', 'first_name', 'last_name', 'is_active', 'date_joined', 'is_staff')

admin.site.register(User, UserAdmin)



回答4:


Might want to try this:

https://libraries.io/pypi/django-modeladmin-reorder

Custom ordering for the apps and models in the admin app. You can also rename, cross link or exclude models from the app list.




回答5:


How can I get the new User model to show up under "Authentication and Authorization"

I had the same concern using Django 3.0, this is how I solved it :

class CustomUser(AbstractUser):
    
     class Meta:
         db_table = 'auth_user'
         app_label = 'auth'

In settings :

AUTH_USER_MODEL = "auth.CustomUser"


来源:https://stackoverflow.com/questions/36046698/register-custom-user-model-with-admin-auth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!