Register user user model with admin auth

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

class User(AbstractUser): company = models.ForeignKey(Company, null=True, blank=True) 

This model is defined in my application, for example MyApp.models .

How can I get a new User model to display in the Authentication and Authorization section as the original django.contrib.auth model?

enter image description here

+11
source share
4 answers

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) 
0
source
 class User(AbstractUser): class Meta: app_label = 'auth' 

This may solve your problem, but may cause some errors when porting the application. Another hack define get_app_list in your AdminSite .

0
source

I think you are looking to replace the Django user model. To do this, see the answer in this post: Extending the User Model with Custom Fields in Django . I would suggest to go along the extended route, but this would mean that the parent and child models must be registered.

If you really want one model, just set the AUTH_USER_MODEL setting for your model. Essentially, this replaces the default model.

In your settings.py:

 AUTH_USER_MODEL = "appname.UserModelName" 

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

0
source

You need to import your custom user model, not the original version of django.contrib.auth.models.User.

So that should only work with

 from django.contrib.auth.admin import UserAdmin from myapp.models import CustomUser admin.site.register(CustomUser, UserAdmin) 

in your admin.py

-1
source

Source: https://habr.com/ru/post/1245194/


All Articles