简体   繁体   中英

Logout not working Django 1.9

I'm building a Django website, but my logout is not working. The site consists in two apps, the main app that is public and the student app that is private. In my student app i've put the @login_required decorator in every method, except the logout method. But when i click the logout link in the student app, my page is not redirected to the main app, it goes to another view inside the student app, and when i reload the page, the content is still available although i've put the @login_required decorator. Here is my code:

website/urls.py

from main_app import urls as main_urls
from student_app import urls as std_urls

urlpatterns = [
url(r'^index/', include(main_urls)),
url(r'^student-area/', include(std_urls))]

website/settings.py

LOGIN_URL = '/index/login/'
LOGIN_REDIRECT_URL = '/student-area/'

main_app/urls.py

...
urlpatterns = [
url(r'^$', views.index, name='index'),
...]

student_app/urls.py

...
urlpatterns = [
url(r'^$', views.std_videos_view, name='student_area'),
url(r'^(?P<video_key>[a-zA-Z0-9\_\.]+)/$', views.std_video_detail_view, name='video_detail'),
url(r'^materials-std/$', views.std_material_view, name='materials_std_view'),
url(r'^download-material/(?P<material_key>[a-zA-Z0-9\_\.]+)/$', views.std_material_download, name='download_material'),
url(r'^sims/$', views.std_sim_view, name='sims_view'),
url(r'^download-sim/(?P<sim_key>[a-zA-Z0-9\_\.]+)/$', views.std_sim_download, name='download_sim'),
url(r'^contact/$', views.std_contact_view, name='std_contact'),
url(r'^logout/$', views.user_logout, name='user_logout')
]

student_app/views.py

from django.contrib.auth import logout
from django.shortcuts import redirect
...
def user_logout(request):
    logout(request)
    return redirect('index')

student_app/templates/student_area.html

...
<a href={% url 'user_logout' %} class="btn btn-default">Logout</a>
...

I am lost in this problem, thank you in advance.

Your video_detail URL pattern matches /logout/ . Django stops as soon as it finds a match, so requests for /logout/ will be handled by the std_video_detail_view view instead of the user_logout view.

You can fix this by either changing the regex for the video_detail URL so that it doesn't clash (for example you could use ^videos/(?P<video_key>[a-zA-Z0-9\\_\\.]+)/$ ), or by moving the logout URL pattern above the video detail pattern.

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