Django通用登录视图会自动创建变量吗?

时间:2014-01-12 23:25:48

标签: python django variables login django-generic-views

我正在使用django通用登录视图。这是我的urls.py

from django.contrib.auth.views import login
....
url(r'^login/$', login),

这是我的login.html页面:

<body>
<h1>User Login</h1>

{% if form.errors %}
    <p>Your username and password did not match. 
    Please try again.</p>
{% endif %}
<form method="post" action="">{% csrf_token %}
    <p><label for="id_username">Username:</label>
    {{ form.username }}</p>

    <p><label for="id_password">Password:</label>
    {{ form.password }}</p>

    <input type="hidden" name="next" />
    <input type="submit" value="login" />
</form>
</body>

这是通用登录视图:

def login(request, template_name='registration/login.html',
      redirect_field_name=REDIRECT_FIELD_NAME,
      authentication_form=AuthenticationForm,
      current_app=None, extra_context=None):
"""
Displays the login form and handles the login action.
"""
redirect_to = request.REQUEST.get(redirect_field_name, '')
if request.method == "POST":
    form = authentication_form(data=request.POST)
    if form.is_valid():

        # Ensure the user-originating redirection url is safe.
        if not is_safe_url(url=redirect_to, host=request.get_host()):
            redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

        # Okay, security check complete. Log the user in.
        auth_login(request, form.get_user())

        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()

        return HttpResponseRedirect(redirect_to)
else:
    form = authentication_form(request)

request.session.set_test_cookie()

current_site = get_current_site(request)

context = {
    'form': form,
    redirect_field_name: redirect_to,
    'site': current_site,
    'site_name': current_site.name,
}
if extra_context is not None:
    context.update(extra_context)
return TemplateResponse(request, template_name, context,
                        current_app=current_app)

现在,一旦我成功登录,它就会重定向到主页,因为在我的settings.py中,

LOGIN_REDIRECT_URL='/'

这是我的主页视图:

def main_page(request):
variables = {
 'head_title': 'Django Bookmarks',
'page_title': 'Welcome to Django Bookmarks',
'page_body': 'Where you can store and share bookmarks!',   
}
return render(request, 'main_page.html', variables)

这是我的主页模板(main_page.html):

<body>
{% if user.username %}
    <p>Welcome {{ user.username }}</p>
{% else %}
<p>Welcome unknown user, please <a href='/login'>Login</a> in order to get full access to the website.</p>
{% endif %}
<h1>{{ page_title }}</h1>
<p>{{ page_body }}</p>
</body>

现在,出于某种原因,

{% if user.username %}
我签署用户后,

行执行为true,即使在我的主页视图中,我甚至没有创建“用户”变量/对象。我想知道,变量“用户”究竟在哪里创建,以及如何将变量作为变量发送到我的main_page.html模板?

2 个答案:

答案 0 :(得分:5)

user变量由auth模块的上下文处理器注入。

请参阅source

答案 1 :(得分:1)

这是AuthenticationMiddleware分配request.user(保证是UserAnonymousUser之一),然后auth上下文处理器公开{{1} } {},request.user