'AnonymousUser'对象没有属性"配置文件"。- 匿名和经过身份验证的用户访问视图



我有以下用户模式:

class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True, null=True)
username = models.CharField(_('username'), max_length=30, null=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
objects = UserManager()
USERNAME_FIELD = "email"
def __str__(self):
return "@{}".format(self.email)

我有UserProfile

class UserProfile(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='profile'
)

根据以前的模型,一个用户有一个用户配置文件。好吧。

我有一些观点,有趣的是匿名用户和登录用户都可以访问它们。

当登录用户访问查看时,这会询问配置文件数据信息并将其显示在模板中

当匿名用户访问查看时,这应该呈现模板,显然没有配置文件数据信息。

此视图名为article_detail,其小逻辑如下:

def article_detail(request, slug):
user = request.user
# I ask fot the profile user 
profile = user.profile
queryset = Article.objects.filter(published_date__lte=timezone.now())
article = get_object_or_404(Article, slug=slug)
return render(request, 'blog/article_detail.html',
{'article': article,'userprofile':profile })

当经过身份验证的用户访问此视图时,将呈现数据配置文件信息,验证profile = user.profile部分代码。这没关系。

但是当匿名用户访问此视图时,我收到消息:

'AnonymousUser' object has no attribute 'profile'  

当用户执行请求时,我尝试使用is_authenticated()函数:

def article_detail(request, slug):
user = request.user
if user.is_authenticated():
profile = user.profile
queryset = Article.objects.filter(published_date__lte=timezone.now())
article = get_object_or_404(Article, slug=slug)
context = {'article': article, 'userprofile':profile }
return render(request, context,
'blog/article_detail.html')

但是当我在用户未进行身份验证时访问视图时,我收到以下消息:

The view blog.views.article_detail didn't return an HttpResponse object. It returned None instead

当我访问用户进行身份验证时查看时,我收到以下消息:

raise TemplateDoesNotExist(template_name, chain=chain)
django.template.exceptions.TemplateDoesNotExist: {'comments': <QuerySet []>, 'article': <Article: Los gatos callejeros>, 'userprofile': <UserProfile: @botibagl@gmail.com>}
[12/Aug/2017 00:01:07] "GET /article/los-gatos-callejeros/ HTTP/1.1" 500 105628

我的问题可能是识别吗?

您的视图不适用于经过身份验证的用户,因为在此行中:

return render(request, context,
'blog/article_detail.html')

您使用context切换了模板名称 - 它应该是:

return render(request, 'blog/article_detail.html', context)

要使视图与匿名用户一起使用,它必须返回 HttpResponse,您的版本返回None。您可以像这样重写视图:

def article_detail(request, slug):
user = request.user
article = get_object_or_404(Article, slug=slug)
context = {'article': article}
if user.is_authenticated():
context['profile'] = user.profile
return render(request, 'blog/article_detail.html', context)

你得到用户作为匿名用户的唯一原因是你没有登录或用户没有经过身份验证,所以请在打开应用程序的那一刻登录到您的帐户。并且问题已解决

相关内容

最新更新