0

我有一个这样的数据库:

from django.db import models


class User(models.Model):
    firstName = models.CharField(max_length=30, blank=False, default=None)
    lastName = models.CharField(max_length=30, blank=False, default=None)
    email = models.EmailField(max_length=100, blank=False, default=None)
    password = models.CharField(max_length=100, blank=False, default=None)
    score = models.IntegerField(default=0)

views.py我想发送一个user当前登录的并在模板中从数据库中显示其信息。
我的views.py

user = User.objects.filter(email=request.POST['email'])
#some code ....
context = RequestContext(request, {
    'user': user[0]
})
return HttpResponse(template.render(context))

我的模板:

{% if user %}
    Wellcome {{ user.firstName }}
{% endif %}

welcome但是当我使用这个时,我也看不到任何东西:

{% if user %}
    Wellcome {{ user }}
{% endif %}

我明白welcome anonymousUser我错在哪里了?

4

2 回答 2

2

You cannot use user as the context variable, as it conflicts with the user object that is injected into the context by the processor

django.contrib.auth.context_processors.auth

Now, to fix your issue, rename user to user_obj or something which makes more sense.

Read more here

于 2013-10-18T18:27:01.553 回答
1

根据您描述的行为,您可能不会从调用过滤器中返回任何对象:

user = User.objects.filter(email=request.POST['email'])

我会查看返回的值,request.POST['email']并确保该值在您的数据库中作为起点。

此外,您应该知道过滤器函数返回的是QuerySet而不是 User 对象。如果要检索唯一的用户对象,可以使用get 函数

于 2013-10-18T17:46:43.373 回答