Django中的用户身份验证

Enr*_* Jr -1 python authentication django django-templates

几个月前我学会了如何在Django中对用户进行身份验证,但是我已经升级并遇到了一些问题,所以我今天早上发现我可能从一开始就没有这么做,所以我决定问一下.

在我的项目的urls.py文件中,我有^ accounts/login/$和^ accounts/logout/$都连接到内置的login()和logout()视图(在django.contrib.auth.views)和^ accounts/profile/$连接到我写的视图,名为"start_here",其内容基本上是这样的:

def start_here(request):
    if request.user:
        user_obj = request.user
    else:
        user_obj = None
    is_auth = False
    if request.user.is_authenticated():
        is_auth = True
    return render_to_response("profile.html", {'auth': is_auth,'user': user_obj,})
Run Code Online (Sandbox Code Playgroud)

现在,"profile.html"扩展了一个名为master.html的主模板,里面是一个"navbar"块,如果'auth'== True(下面的代码段),其内容应该会改变

{% block navbar %}
            {% if auth %}
                <a href="">Link A</a>
                <a href="">Link B</a>
                <a href="">Link C</a>
                <a href="">Link D</a>
                <a href="">Link E</a>
                <a href="">Link F</a>
                <a href="/accounts/logout/">Logout</a>
            {% else %}
                <a href="/accounts/login/">Login</a>
            {% endif %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我登录并重定向到/ accounts/profile时,导航栏不会显示Links AF + Logout,它只显示"login".除非我手动将上面的块复制粘贴到profile.html中,否则它不会按照我的预期方式工作.调用render_to_response()时,我提供的上下文是否会传递给父模板以及子模板?

master和profile.html的完整源代码:http://dpaste.com/hold/128784/ 我在代码中看不到任何可疑内容.

Ala*_*air 6

这个答案是切不过的,但Jim建议使用RequestContext是如此之好,我想明确解释如何做到这一点.

你可以减少你的start_here功能

from django.template import RequestContext

def start_here(request):
    return render_to_response("profile.html", {},
        context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

通过使用RequestContext,user会自动添加到上下文中.而不是使用

{% if auth %}
Run Code Online (Sandbox Code Playgroud)

使用

{% if user.is_authenticated %}
Run Code Online (Sandbox Code Playgroud)