我试图创建一个自定义用户,但是有一个问题,当我收到request.user时,它是User的一个实例,而不是CustomUser的实例,所以我没有得到额外的字段和方法。我找到了this,但是当我尝试登录django管理员时,它再也无法工作了。
这是我的代码: models.py
class CustomUser(User):
timezone = models.CharField(max_length=50, default='Europe/Bucharest')
porecla = models.CharField(max_length=50, null=True)
selectat = models.BooleanField(default=False)
objects = UserManager()
auth_backends.py - 所以我可以在使用request.user
时使用自定义用户的方法from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.apps import apps
class CustomUserModelBackend(ModelBackend):
def authenticate(self, username=None, password=None):
try:
user = self.user_class.objects.get(username=username)
if user.check_password(password):
return user
except self.user_class.DoesNotExist:
return None
def get_user(self, user_id):
try:
return self.user_class.objects.get(pk=user_id)
except self.user_class.DoesNotExist:
return None
@property
def user_class(self):
if not hasattr(self, '_user_class'):
self._user_class = apps.get_model(*settings.CUSTOM_USER_MODEL.split('.', 2))
if not self._user_class:
raise ImproperlyConfigured('Could not get custom user model')
return self._user_class
settings.py
AUTHENTICATION_BACKENDS = ('football_app.auth_backends.CustomUserModelBackend', )
CUSTOM_USER_MODEL = 'football_app.CustomUser'
admin.py
class CustomUserAdmin(admin.ModelAdmin):
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'selectat', )
admin.site.register(CustomUser, CustomUserAdmin)