1

您好我正在尝试在我的基本模板中使用用户对象,但即使在登录页面后用户对象每次都返回空值

请在这里找到我的代码:

意见:

def loginView(request):
    if request.POST:
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username =username, password = password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/rango/home/')
        else: 
            print 'No user exist'
    else:
        c= {}
        c.update(csrf(request))
        return render_to_response('login.html', c)     

基础模板

<diV style="float: left;">
{% block sidebar %}
<div>
{% if user.is_authenticated %}
<a href="{%url 'addCategory'  %}">Add Category</a></br>
<a href="{%url 'logout' %}">Logout</a>
{% endif %}
<a href="{%url 'register'%}">Register</a></br>
<a href="{%url 'login'%}">Login</a></br>
<a href="{%url 'about'  %}" >About</a></br>
</div>
{% endblock %}
</diV>
4

3 回答 3

2

将您的代码更改为

return render_to_response('login.html', c, 
            context_instance=RequestContext(request))

没有context_instancedjango 将不会在模板上下文中添加默认上下文处理器数据。所以你没有user在模板中得到对象。

于 2013-11-11T16:30:00.317 回答
0

{% if request.user.is_authenticated %}在您的模板中尝试。

于 2013-11-11T16:27:06.430 回答
0

如果您确保启用了处理器,您的模板中django.contrib.auth.context_processors.auth应该只有一个可用的变量。user

默认情况下启用此处理器,但如果您TEMPLATE_CONTEXT_PROCESSORS在设置中进行了覆盖,则可能已禁用它。

于 2013-11-11T16:35:43.500 回答