在 Django 中使用自定义用户模型总是 return 模板中的匿名用户
Using custom user model in Django always return anonymous user in template
我创建了一个自定义用户模型,因为我需要三个信息(电子邮件、学院 ID、密码)才能登录系统。为此,我还创建了一个身份验证后端。当我尝试登录时,它会重定向到正确的视图。但是模板显示匿名用户而不是登录用户。它不会进入这种情况 {% if user.is_authenticated %}。但是,user.is_authenticated在视图中是正确的。谁能帮我解决问题?任何建议将不胜感激。我在下面附上了我的代码。提前致谢。
model.py
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, center_id, password, **extra_fields):
values = [email, center_id]
field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values))
for field_name, value in field_value_map.items():
if not value:
raise ValueError('The {} value must be set'.format(field_name))
email = self.normalize_email(email)
user = self.model(
email=email,
center_id=center_id,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, center_id, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, center_id, password, **extra_fields)
def create_superuser(self, email, center_id, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, center_id, password, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='email address',max_length=255,unique=True,)
first_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
center_id = models.CharField(max_length=50)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
last_login = models.DateTimeField(null=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['center_id']
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def has_perm(self, perm, obj=None):
return True
def email_user(self, subject, message, from_email=None, **kwargs):
send_mail(subject, message, from_email, [self.email], **kwargs)
def has_module_perms(self, app_label):
return True
backend.py
from django.contrib.auth import get_user_model
from authentication.models import User
from django.db.models import Q
class AuthBackend(object):
supports_object_permissions = True
supports_anonymous_user = False
supports_inactive_user = False
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
def authenticate(self, email=None, password=None, center_id=None):
usermodel = get_user_model()
try:
user = usermodel.objects.get(Q(email__iexact=email) & Q(center_id__iexact=center_id))
if user.check_password(password):
return user
except ObjectDoesNotExist:
return None
settings.py
AUTHENTICATION_BACKENDS = (
'accounts.backends.AuthBackend',
'django.contrib.auth.backends.ModelBackend',
)
AUTH_USER_MODEL = 'authentication.User'
view.py:
def userLoginView(request):
if request.method == 'POST':
center_id = request.POST.get('center_id')
email = request.POST.get('email')
password = request.POST.get('password')
request.session['center_id'] = center_id
request.session['email'] = email
user = AuthBackend.authenticate(request, email=email, password=password, center_id=center_id)
if user:
if user.is_active:
auth_login(request, user, backend='fileupload_project.accounts.backends.AuthBackend')
if user.is_authenticated:
print('authenticated')
return redirect('accounts:search')
else:
return HttpResponse("Your account is disabled.")
else:
return HttpResponseRedirect(reverse('accounts:login'))
else:
return render(request, 'accounts/registration/login.html', {})
def searchPatientView(request):
return render(request,'accounts/patient_registration/search.html',{})
template/search.html:
<div class="col-sm-8 text-left">
{{ user }}
{% if user.is_authenticated %}
{{ user.email }}
{% endif %}
</div>
尝试!
{% 如果 request.user.is_authenticated %}
我的问题已经解决了。虽然这是一个愚蠢的错误。我没有正确调用我的自定义身份验证后端。因此,系统从不使用它进行身份验证。我对 view.py 和 settings.py 进行了更改。我已经在下面发布了更新版本。
view.py:
if user.is_active:
auth_login(request, user, backend='accounts.backends.AuthBackend')
if user.is_authenticated:
print('authenticated')
return redirect('accounts:search')
settings.py:
AUTHENTICATION_BACKENDS = (
'accounts.backends.AuthBackend',
#'django.contrib.auth.backends.ModelBackend',
)
AUTH_USER_MODEL = 'authentication.User'
我创建了一个自定义用户模型,因为我需要三个信息(电子邮件、学院 ID、密码)才能登录系统。为此,我还创建了一个身份验证后端。当我尝试登录时,它会重定向到正确的视图。但是模板显示匿名用户而不是登录用户。它不会进入这种情况 {% if user.is_authenticated %}。但是,user.is_authenticated在视图中是正确的。谁能帮我解决问题?任何建议将不胜感激。我在下面附上了我的代码。提前致谢。
model.py
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, center_id, password, **extra_fields):
values = [email, center_id]
field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values))
for field_name, value in field_value_map.items():
if not value:
raise ValueError('The {} value must be set'.format(field_name))
email = self.normalize_email(email)
user = self.model(
email=email,
center_id=center_id,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, center_id, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, center_id, password, **extra_fields)
def create_superuser(self, email, center_id, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, center_id, password, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='email address',max_length=255,unique=True,)
first_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
center_id = models.CharField(max_length=50)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
last_login = models.DateTimeField(null=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['center_id']
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def has_perm(self, perm, obj=None):
return True
def email_user(self, subject, message, from_email=None, **kwargs):
send_mail(subject, message, from_email, [self.email], **kwargs)
def has_module_perms(self, app_label):
return True
backend.py
from django.contrib.auth import get_user_model
from authentication.models import User
from django.db.models import Q
class AuthBackend(object):
supports_object_permissions = True
supports_anonymous_user = False
supports_inactive_user = False
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
def authenticate(self, email=None, password=None, center_id=None):
usermodel = get_user_model()
try:
user = usermodel.objects.get(Q(email__iexact=email) & Q(center_id__iexact=center_id))
if user.check_password(password):
return user
except ObjectDoesNotExist:
return None
settings.py
AUTHENTICATION_BACKENDS = (
'accounts.backends.AuthBackend',
'django.contrib.auth.backends.ModelBackend',
)
AUTH_USER_MODEL = 'authentication.User'
view.py:
def userLoginView(request):
if request.method == 'POST':
center_id = request.POST.get('center_id')
email = request.POST.get('email')
password = request.POST.get('password')
request.session['center_id'] = center_id
request.session['email'] = email
user = AuthBackend.authenticate(request, email=email, password=password, center_id=center_id)
if user:
if user.is_active:
auth_login(request, user, backend='fileupload_project.accounts.backends.AuthBackend')
if user.is_authenticated:
print('authenticated')
return redirect('accounts:search')
else:
return HttpResponse("Your account is disabled.")
else:
return HttpResponseRedirect(reverse('accounts:login'))
else:
return render(request, 'accounts/registration/login.html', {})
def searchPatientView(request):
return render(request,'accounts/patient_registration/search.html',{})
template/search.html:
<div class="col-sm-8 text-left">
{{ user }}
{% if user.is_authenticated %}
{{ user.email }}
{% endif %}
</div>
尝试!
{% 如果 request.user.is_authenticated %}
我的问题已经解决了。虽然这是一个愚蠢的错误。我没有正确调用我的自定义身份验证后端。因此,系统从不使用它进行身份验证。我对 view.py 和 settings.py 进行了更改。我已经在下面发布了更新版本。 view.py:
if user.is_active:
auth_login(request, user, backend='accounts.backends.AuthBackend')
if user.is_authenticated:
print('authenticated')
return redirect('accounts:search')
settings.py:
AUTHENTICATION_BACKENDS = (
'accounts.backends.AuthBackend',
#'django.contrib.auth.backends.ModelBackend',
)
AUTH_USER_MODEL = 'authentication.User'