简体   繁体   中英

django user authenticated (not authenticated )

I want to create a simple Django authentication (register/login/logout) but I have problems. if complete login successfully then app go to next page with name mypage because I have define in my settings.py that line : LOGIN_REDIRECT_URL = '/mypage' .

but in the new page user is not authenticated user(my user stay authenticated only in the "/login" and "/register" page but not in home and mypage )

any idea why I have wrong ?

here the code :

urls.py

url(r'^$', views.home),
url(r'^mypage/$', views.mypage),
url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}),
url(r'^logout/$', views.logout, {'next_page': '/login/'}),
url(r'^register/$', views.register),
url(r'^register/success/$', views.register_success)

views.py

def home(request):
    return render_to_response('home.html')

def mypage(request):
    return render_to_response('home2.html')

settings.py

LOGIN_REDIRECT_URL = '/mypage'

html 1 :

        {% if user.is_authenticated %}
         <li>
            <a href="/logout">LogOut</a>
        </li>
        {% else %}
         <li>
            <a href="/login">Login</a>
        </li>
        {% endif %}

html 2 :

{% if user.is_authenticated %}
 <a href="#" class="lg">Start</a>
  {% else %}
  <p>Please Login to start</p>
  {% endif %}

In urls.py

from django.contrib.auth import views as auth_views

urlpatterns = [
    url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'),
    url(r'^logout/$', auth_views.logout, name='logout'),
    . . .. 
]

In login.html

{% extends 'base.html' %}

{% block title %}Login{% endblock %}

{% block content %}
   <h2>Login</h2>
   <form method="post">
   {% csrf_token %}
   {{ form.as_p }}
   <button type="submit">Login</button>
 </form>
{% endblock %}

when you use render_to_response you need add user to context manual, or you can use render with request, in this case user will be added to your template context

from django.shortcuts import render, render_to_response

def home(request):
    return render(request, 'home.html')

def mypage(request):
    return render_to_response('home2.html', {'user': request.user})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM