在 Django 中使用自定义用户模型总是在模板中返回匿名用户
Posted
技术标签:
【中文标题】在 Django 中使用自定义用户模型总是在模板中返回匿名用户【英文标题】:Using custom user model in Django always return anonymous user in template 【发布时间】:2020-09-30 11:56:31 【问题描述】:我创建了一个自定义用户模型,因为我需要三个信息(电子邮件、机构 ID、密码)来登录系统。为此,我还创建了一个身份验证后端。当我尝试登录时,它会重定向到正确的视图。但模板显示匿名用户而不是登录用户。它不会进入这种情况 % if user.is_authenticated %。但是,user.is_authenticated 在视图中是 true。谁能帮我解决问题?任何建议将不胜感激。我在下面附上了我的代码。提前致谢。
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',)
模板/搜索.html:
<div class="col-sm-8 text-left">
user
% if user.is_authenticated %
user.email
% endif %
</div>
【问题讨论】:
【参考方案1】:试试吧!
% if request.user.is_authenticated %
【讨论】:
感谢您的回复。我也试过了,仍然有匿名用户。实际上,当登录视图重定向到另一个视图(搜索视图)时,它会发送匿名用户。不知道我应该在哪里改变才能使它正确。 在身份验证期间,永远不会调用 get_user(self, user_id) 函数。 Django 框架对我来说是新的。请帮我解决它。【参考方案2】:我已经解决了我的问题。虽然这是一个愚蠢的错误。我没有正确调用我的自定义身份验证后端。因此,系统从不使用它进行身份验证。我在 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'
【讨论】:
以上是关于在 Django 中使用自定义用户模型总是在模板中返回匿名用户的主要内容,如果未能解决你的问题,请参考以下文章