I have a custom user model:
class CustomUser(AbstractUser):
ACCESS_LEVELS = (
('user', 'Авторизованный пользователь'),
('admin', 'Администратор')
)
email = models.EmailField(
max_length=254,
unique=True,
verbose_name='Эл. почта'
)
access_level = models.CharField(
max_length=150,
choices=ACCESS_LEVELS,
blank=True,
default='user',
verbose_name='Уровень доступа',
)
@property
def is_admin(self):
return self.is_superuser or self.access_level == 'admin'
class Meta:
verbose_name = 'Пользователь'
verbose_name_plural = 'Пользователи'
def __str__(self):
return (
f'email: {self.email}, '
f'access_level: {self.access_level}'
)
Registered in the admin panel:
@admin.register(CustomUser)
class UserAdmin(admin.ModelAdmin):
list_display = ('username', 'email', 'access_level')
search_fields = ('email', 'access_level')
list_filter = ('email',)
def save_model(self, request, obj, form, change):
if obj.is_admin:
obj.is_staff = True
obj.save()
When I create a superuser or a user with staff status and try to log in, a message appears:
Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.
So I Googled the issue and tried everything I could. Here are all the problems I investigated:
Database not synced: I synced it and nothing changed.
No django_session table: I checked; it's there.
Problematic settings: I just added the created apps to INSTALLED_APPS.
User not configured correctly: is_staff, is_superuser, and is_active are all True.
Old sessions: I checked the django_session table and it's empty.
Missing or wrong URL pattern: Currently I have url('admin/', admin.site.urls) in mysite/urls.py.
Wrong server command: I'm using python manage.py runserver.
Something wrong with database: I tried deleting the database and then reapplying the migrations, but nothing changed.
CodePudding user response:
Use UserAdmin
[Django-GitHub] to register UserModel. It will provide the functionality to hash the password when you enter the password in admin panel so:
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
pass
admin.site.register(CustomUser, CustomUserAdmin)