You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django自定义JWT认证失效:后台登录失败问题求助

Hey there, let's break down why you're hitting that admin login error with your custom Django user model and JWT setup. Here are the most common fixes to get you sorted:

1. First, confirm your users have is_staff=True

The error message explicitly calls out needing a "staff account"—this is the most likely culprit. Django's admin requires users to have the is_staff flag enabled to access the backend.

  • Check your existing users via the Django shell:
    python manage.py shell
    from your_app.models import CustomUser
    user = CustomUser.objects.get(email="your_user_email@example.com")
    print(user.is_staff)  # This should return True
    
  • If it returns False, update and save the user:
    user.is_staff = True
    user.save()
    
2. Verify your CustomAuthBackend works for admin authentication

Your custom backend needs to correctly validate users and return valid user instances (with is_active=True—the admin will handle the is_staff check separately).

  • Ensure your backend's authenticate method looks something like this:
    class CustomAuthBackend:
        def authenticate(self, request, email=None, password=None, **kwargs):
            try:
                user = CustomUser.objects.get(email=email)
                # Only return the user if password is correct AND account is active
                if user.check_password(password) and user.is_active:
                    return user
            except CustomUser.DoesNotExist:
                return None
    
        def get_user(self, user_id):
            try:
                return CustomUser.objects.get(pk=user_id)
            except CustomUser.DoesNotExist:
                return None
    
  • Don't forget to register it in settings.py:
    AUTHENTICATION_BACKENDS = [
        'your_app.backends.CustomAuthBackend',
        # Optional: Keep the default ModelBackend as a fallback
        'django.contrib.auth.backends.ModelBackend',
    ]
    
3. Make sure your CustomUser is properly registered with the admin

If you haven't set up a custom admin class for your CustomUser, Django might not recognize or display the is_staff field correctly.

  • Create a custom admin class in admin.py and register your user model:
    from django.contrib import admin
    from django.contrib.auth.admin import UserAdmin
    from .models import CustomUser
    
    class CustomUserAdmin(UserAdmin):
        # Customize how users are displayed in the admin
        list_display = ('email', 'first_name', 'last_name', 'is_staff', 'is_active')
        list_filter = ('is_staff', 'is_active')
        # Define fields shown when editing a user
        fieldsets = (
            (None, {'fields': ('email', 'password')}),
            ('Personal Info', {'fields': ('first_name', 'last_name')}),
            ('Permissions', {'fields': ('is_staff', 'is_active', 'is_superuser', 'groups', 'user_permissions')}),
            ('Important Dates', {'fields': ('last_login', 'date_joined')}),
        )
        # Define fields shown when creating a new user
        add_fieldsets = (
            (None, {
                'classes': ('wide',),
                'fields': ('email', 'password1', 'password2', 'is_staff', 'is_active')
            }),
        )
        search_fields = ('email',)
        ordering = ('email',)
    
    admin.site.register(CustomUser, CustomUserAdmin)
    
4. Rule out JWT interference

JWT is designed for API auth and shouldn't break admin session auth, but double-check your middleware setup to be safe:

  • Ensure django.contrib.auth.middleware.AuthenticationMiddleware is present in your MIDDLEWARE list in settings.py—this handles admin session authentication.
  • Keep JWT-specific middleware (like rest_framework_simplejwt.middleware.AuthenticationMiddleware) in the correct order, so it doesn't override the default admin auth flow.
5. Test with a fresh superuser

If all else fails, create a new superuser using Django's built-in command to see if the issue is with your existing users:

python manage.py createsuperuser

If this new user can log into the admin, your original users likely had missing permissions or incorrect field values.

Start with checking the is_staff status first—that's exactly what the error message is flagging. Then work through the other checks to align your custom setup with Django's admin requirements.

内容的提问来源于stack exchange,提问作者Satendra Pratap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:07:30