我正在使用django通用登录视图.这是我的urls.py
from django.contrib.auth.views import login .... url(r'^login/$', login),
这是我的login.html页面:
User Login
{% if form.errors %}Your username and password did not match. Please try again.
{% endif %}
这是通用登录视图:
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):
{% if user.username %}Welcome {{ user.username }}
{% else %}Welcome unknown user, please Login in order to get full access to the website.
{% endif %}{{ page_title }}
{{ page_body }}
现在,由于某种原因,
{% if user.username %}
在我签署用户后,line执行为true,即使在我的主页视图中,我甚至没有创建"用户"变量/对象.我想知道,变量"用户"究竟在哪里创建,以及如何将变量作为变量发送到我的main_page.html模板?
该user
变量由auth模块的上下文处理器注入.
见源