Я использую общий вид входа в django. Это мой urls.pyОбщий вид входа в Django автоматически создает переменную?
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)
Теперь, когда я успешно войти, он перенаправляет меня на домашнюю страницу, так как в моих настройках.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?
BTW у вас также есть «perms» в вашем шаблоне (https://docs.djangoproject.com/en/dev/ref/templates/api/#django-contrib-auth-context-processors-auth) – furins