Home > Mobile >  Show fields for adding password to custom user model - Django
Show fields for adding password to custom user model - Django

Time:06-28

I have a custom user model. I want the admin to create new accounts from the admin panel. Registering a class doesn't help.

admin.site.register(CustomUser)

*This has the effect of avoiding the possibility of double-entering the password

So I try this solution:

from django.contrib.auth.admin import UserAdmin

admin.site.register(CustomUser, UserAdmin)

*In the above option, I have the option to enter the password twice (whean i create user), but the other fields from my custom user model are disappearing.

class CustomUser(AbstractUser):
    name = models.CharField(max_length=50, blank=True, null=True)
    surname = models.CharField(max_length=50, blank=True, null=True)
    account_type = models.ForeignKey(Locationd, on_delete=models.CASCADE, blank=True, null=True

How to add the ability to create accounts in the admin panel, giving a password that can be sent to the new user and editing all fields from the custome user class.

)

CodePudding user response:

You can use your own Django form

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

class ManagingUsers(UserAdmin):

    add_form = SignUpForm

    list_display = ['__str__']
    search_fields = ['email']
    readonly_fields = ['date_joined', 'last_login']
    ordering = ('id',)

    filter_horizontal = []
    list_filter = []


    add_fieldsets = (

        ('Add a new user', {
            'classes':('wide',),
            'fields': ('first_name', 'last_name' ,'email', 'birthday', 'password1', 'password2', 'avatar', 'cover_pic', 'validated', 'is_admin', 'is_staff', 'is_active', 'is_superuser'),
            }),
        )
    
    fieldsets = (

        (None, {
            'fields': ('first_name', 'last_name', 'bio' ,'email', 'birthday', 'avatar', 'cover_pic', 'is_admin',  'is_staff', 'is_active', 'is_superuser'),
            }),

        )
admin.site.register(User, ManagingUsers)

This code from an old project so change the fields names to whatever you want

CodePudding user response:

You need to unregister the user model then add your custom user

from django.contrib.auth.models import User

admin.site.unregister(User)
admin.site.register(CustomUser, UserAdmin or YourCustomAdminSettings)
  • Related