Django generic login view creates variable automatically?
我正在使用django通用登录视图。这是我的urls.py
1 2 3 | from django.contrib.auth.views import login .... url(r'^login/$', login), |
这是我的login.html页面:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <body> User Login {% 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> |
这是常规登录视图:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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中,
1 | LOGIN_REDIRECT_URL='/' |
这是我的主页视图:
1 2 3 4 5 6 7 | 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):
1 2 3 4 5 6 7 8 9 | <body> {% if user.username %} <p>Welcome {{ user.username }}</p> {% else %} <p>Welcome unknown user, please Login in order to get full access to the website.</p> {% endif %} {{ page_title }} <p>{{ page_body }}</p> </body> |
现在,由于某种原因,
1 | {% if user.username %} |
即使在首页视图中,我什至没有创建"用户"变量/对象,我登录用户后
行仍会执行为true。我想知道,"用户"变量到底在哪里创建,以及如何作为变量发送到我的main_page.html模板?
请参阅源文件
这是AuthenticationMiddleware分配的