I am using the django generic login view. This is my urls.py
from django.contrib.auth.views import login
....
url(r'^login/$', login),
This is my login.html page:
<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>
This is the generic login view:
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)
Now, Once I successfully log in, it redirects me to the homepage since in my settings.py,
LOGIN_REDIRECT_URL='/'
This is my homepage view:
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)
and this is my homepage template (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>
Now, for some reason, the
{% if user.username %}
line executes to true after I sign the user in, even though in my homepage view, I didn't even create a 'user' variable / object. I'm wondering, where exactly is the variables 'user' created and how is it being sent as a variables to my main_page.html template?
The user
variable is injected by a context processor of the auth module.
See source