gpt4 book ai didi

python - 在 django 上获取用户返回 "AnonymousUser"

转载 作者:太空宇宙 更新时间:2023-11-03 18:47:16 24 4
gpt4 key购买 nike

我关注了这个tutorial创建自定义用户。在views.py中,我创建了一个通过用户ID(即/users/42)预设用户信息的方法,但结果是AnonymousUser。我应该提到我试图获取的数据库记录存在于我的数据库中。

这是我的 models.py 文件:

from django import forms
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.contrib.auth.forms import UserCreationForm

class UserProfileManager(BaseUserManager):
def create_user(self, email, date_of_birth, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')

user = self.model(
email=self.normalize_email(email),
date_of_birth=date_of_birth,
)

user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, email, date_of_birth, password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(email,
password=password,
date_of_birth=date_of_birth
)
user.is_admin = True
user.save(using=self._db)
return user


class UserProfile(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
db_index=True,
)
date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)

objects = UserProfileManager()

USERNAME_FIELD = 'email'
#REQUIRED_FIELDS = ['date_of_birth']

def get_full_name(self):
# The user is identified by their email address
return self.email

def get_short_name(self):
# The user is identified by their email address
return self.email

# On Python 3: def __str__(self):
def __unicode__(self):
return self.email

def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True

def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True

@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin


class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

class Meta:
model = UserProfile
fields = ('email', 'date_of_birth')

def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2

def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user

这是显示用户的方法:

def show_user(request, user_id):
try:
user = UserProfile.objects.get(id=user_id)
except UserProfile.DoesNotExist:
return None
template = loader.get_template('index.html')
context = RequestContext(request, {
'user': user,
})
return HttpResponse(template.render(context))

最佳答案

django.contrib.auth.context_processors.authuser 变量注入(inject)到上下文数据中,上下文处理器注入(inject)的变量可以覆盖提供给 RequestContext 的变量。

When context processors are applied

When you use RequestContext, the variables you supply directly are added first, followed any variables supplied by context processors. This means that a context processor may overwrite a variable you’ve supplied, so take care to avoid variable names which overlap with those supplied by your context processors.

Source: https://docs.djangoproject.com/en/dev/ref/templates/api/

关于python - 在 django 上获取用户返回 "AnonymousUser",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19247675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com