when I add new user from admin panel this error HELP!

image

FieldError at /admin/accounts/customuser/add/
Unknown field(s) (usable_password) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin.
Request Method:	GET
Request URL:	http://127.0.0.1:8000/admin/accounts/customuser/add/
Django Version:	5.1.1
Exception Type:	FieldError
Exception Value:	
Unknown field(s) (usable_password) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin.
Exception Location:	C:\Users\Baxti\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\contrib\admin\options.py, line 841, in get_form
Raised during:	django.contrib.auth.admin.add_view
Python Executable:	C:\Users\Baxti\AppData\Local\Programs\Python\Python312\python.exe
Python Version:	3.12.5
Python Path:	
['C:\\Users\\Baxti\\Desktop\\Django-CRM',
 'C:\\Users\\Baxti\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip',
 'C:\\Users\\Baxti\\AppData\\Local\\Programs\\Python\\Python312\\DLLs',
 'C:\\Users\\Baxti\\AppData\\Local\\Programs\\Python\\Python312\\Lib',
 'C:\\Users\\Baxti\\AppData\\Local\\Programs\\Python\\Python312',
 'C:\\Users\\Baxti\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages']
Server time:	Thu, 26 Sep 2024 06:46:21 +0000

accounts/admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser


class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['email','username','first_name','last_name','age','is_staff']
    fieldsets = UserAdmin.fieldsets + (
        (None, {'fields': ('age',)}),
    )
    add_fieldsets = UserAdmin.add_fieldsets + (
        (None,{'fields':('age',)}),
    )

admin.site.register(CustomUser, CustomUserAdmin)

accounts/models.py

from django.contrib.auth.models import AbstractUser
from django.db import models


class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True, blank=True)

accounts/forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
from django.contrib.auth.models import User

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm):
        model = CustomUser
        fields = ('username', 'first_name', 'last_name', 'email',)


class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = ('first_name','last_name','email','age',)



class SignUpForm(UserCreationForm):
    email = forms.EmailField(label="", widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Email'}))
    first_name = forms.CharField(label="", max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Ism'}))
    last_name = forms.CharField(label="", max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Familiya'}))


    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')


    def __init__(self, *args, **kwargs):
        super(SignUpForm, self).__init__(*args, **kwargs)

        self.fields['username'].widget.attrs['class'] = 'form-control'
        self.fields['username'].widget.attrs['placeholder'] = 'Username'
        self.fields['username'].label = ''
        self.fields['username'].help_text = '<span class="form-text text-muted"><small>Qabul qiladi 150 belgilar yoki kamroq. Harflar, raqamlar, va faqat @/./+/-/_ belgialar. </small></span>'

        self.fields['password1'].widget.attrs['class'] = 'form-control'
        self.fields['password1'].widget.attrs['placeholder'] = 'Parol'
        self.fields['password1'].label = ''
        self.fields['password1'].help_text = ('<ul class="form-text text-muted small">'
                                              '<li>Sizning parol ma\'lumotlaringiz bilan bir hil bo\'lmasin!</li>'
                                                     '<li>Sizning parol 8 belgidan kam bo\'lmasin!</li>'
                                              '<li>Sizning parol juda ham oddiy bo\'lmasligi lozim!</li>'
                                              '<li>Sizning parol faqat raqamlardan tashkil topmasligi lozim!</li></ul>')

        self.fields['password2'].widget.attrs['class'] = 'form-control'
        self.fields['password2'].widget.attrs['placeholder'] = 'Parol takroran'
        self.fields['password2'].label = ''
        self.fields['password2'].help_text = '<span class="form-text text-muted"><small>Tastiqlash uchun. Parolni takroran yozing. </small></span>'

accounts/view.py

from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.urls import reverse_lazy
from django.contrib import messages
from django.views.generic import CreateView
from .forms import CustomUserCreationForm, SignUpForm


class SignUpView(CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'registration/register.html'


def register_user(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            # Authenticate and login
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user = authenticate(username=username, password=password)
            login(request, user)
            messages.success(request, "Siz muvaffaqiyatli ro`yhatdan o`tdingiz!")
            return redirect('home')
    else:
        form = SignUpForm()
        return render(request, 'register.html', {'form':form})

    return render(request, 'register.html', {'form':form})


The issue is that you have:

which is extending this from the base UserAdmin class:

    add_fieldsets = (
        (
            None,
            {
                "classes": ("wide",),
                "fields": ("username", "usable_password", "password1", "password2"),
            },
        ),
    )

You can see the usable_password field defined in the add_fieldsets attribute.

Your CustomUserAdmin, which is inheriting from UserAdmin, defines add_form = CustomUserCreationForm. Your CustomUserCreationForm inherits from UserCreationForm.

However, if you look at the UserAdmin class definition, you’ll see that it defines add_form = AdminUserCreationForm.

It looks to me that you’re probably creating your CustomUserCreationForm as inheriting from the wrong class.

1 Like

Then what to do next? Which class to inherit?

1 Like

What form class does the UserAdmin class use for the add_form attribute?

If you’re going to inherit from AbstractUser and modify its behavior, you’re going to want to parallel its settings precisely.

1 Like
class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['email','username','first_name','last_name','age','is_staff']
    fieldsets = UserAdmin.fieldsets + (
        (None, {'fields': ('age',)}),
    )
    # add_fieldsets = UserAdmin.add_fieldsets + (
    #     (None,{'fields':('age',)}),
    # )

    add_fieldsets = (
        (
            None,
            {
                "classes": ("wide",),
                "fields": ("username", "usable_password", "password1", "password2"),
            },
        ),
    )

admin.site.register(CustomUser, CustomUserAdmin)


FieldError at /admin/accounts/customuser/add/

Unknown field(s) (usable_password) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin.

Request Method: GET
Request URL: http://127.0.0.1:8000/admin/accounts/customuser/add/
Django Version: 5.1.1
Exception Type: FieldError
Exception Value: Unknown field(s) (usable_password) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin.
Exception Location: C:\Users\Baxti\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\contrib\admin\options.py, line 841, in get_form
Raised during: django.contrib.auth.admin.add_view
Python Executable: C:\Users\Baxti\AppData\Local\Programs\Python\Python312\python.exe
Python Version: 3.12.5

but nothing to change bro

What did you change here? If you fixed your CustomUserCreationForm, please post the new version.

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm):
        model = CustomUser
        fields = ('username', 'first_name', 'last_name', 'email',)

you said that

What class did I say the UserAdmin class uses for the add_form attribute?

Instead of extending the add_fieldsets from the UserAdmin, rather override the add_fieldsets attribute.
The UserAdmin class inbuilt into django ships with a usable_password attribute which your customuser does not have. So you override that attribute with your own custom fields that does not include usable_password.

add_fieldsets = (
(
None,
{
“classes”: (“wide”,),
“fields”: (“username”,“email”,“age”, “password1”, “password2”),
},
),
)
This should fix it.

2 Likes

thank you very very very much i am so happy its working I love coding keep coding thank you for motivation help
@KenWhitesell @snr-roko thank you so much

1 Like

I’m brand new to this, so I may be wrong: but it appears that this is an error in the fifth edition of Django for Beginners @wsvincent

1 Like

Hi @skillstackwildcat I just encountered the same issue but if you read what @KenWhitesell mentioned, you need to change what CustomUserCreationForm inherits from.

What he’s saying is, you need to look at the UserAdmin class, then look at what add_form field is using. It’s using AdminUserCreationForm. So if we’re going to override add_form for our own custom logic, we need to inherit from AdminUserCreationForm.

I don’t think this is an error in Django for Beginners but I may be wrong. I only have the 4th edition so I’m not familiar with the 5th. I think you should double check the very specific version of Django you have and the one @wsvincent uses. It seems there was a recent change to add_form where it inherits from AdminUserCreationForm instead of UserCreationForm.