Why can't I logout on django user auth?

眉间皱痕 提交于 2019-12-05 04:11:17

You need to have a logout view with the url pointing to that view. Nothing has to be on the template, just have django.contrib.auth.logout() in that logout view. On the new django servers you can eaisly logout, but you need to do this within a view, not a template. Here is an excerpt from the django book:

This example shows how you might use both authenticate() and login() within a view function:

from django.contrib import auth

def login_view(request):
  username = request.POST.get('username', '')
  password = request.POST.get('password', '')
  user = auth.authenticate(username=username, password=password)
  if user is not None and user.is_active:
      # Correct password, and the user is marked "active"
      auth.login(request, user)
      # Redirect to a success page.
      return HttpResponseRedirect("/account/loggedin/")
  else:
      # Show an error page
      return HttpResponseRedirect("/account/invalid/")

To log out a user, use django.contrib.auth.logout() within your view. It takes an HttpRequest object and has no return value:

from django.contrib import auth

def logout_view(request):
  auth.logout(request)
  # Redirect to a success page.
  return HttpResponseRedirect("/account/loggedout/")

Refer to the Django book in terms of everything http://www.djangobook.com/en/2.0/chapter14/, I learned everything from this book.

I've encountered this problem, and it's a stupid headache. This is how I force logging out. I preserve logout(request) to (hopefully) trigger the user logged out signals.:

def logout_view(request):

    logout(request)
    request.session.flush()
    request.user = AnonymousUser

    return HttpResponseRedirect('accounts/loggedout/') 

You don't have to write a view for that, you can just do:

(r'^accounts/logout/$', 'django.contrib.auth.views.logout',{'next_page': '/accounts/login'})

More info: https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.views.logout

mrbox

I think that urls.py could be like this(login and logout views do not accept SSL parameter):

from django.core.urlresolvers import reverse
urlpatterns += patterns('django.contrib.auth.views',
        url(r'^login/$', 'login', { 'template_name': 'registration/login.html'}, name='login' ),
        url(r'^logout/$', 'logout', { 'template_name': 'registration/my_account.html', 'next_page':reverse('index') }, name='logout' ),
)

And in the template:

<h1>My Account</h1>
<strong> Welcome, {{ name|capfirst }}!</strong>
<br /><br />
<ul>
    <li>
        {% if user.is_authenticated %}
            <a href="{% url logout %}">Logout</a>
        {% else %}
            <a href="{% url register %}">Sign Up</a>
    </li>
    <li>
            <a href="{% url login %}">Login</a>
        {% endif %}
    </li>
</ul>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!