简体   繁体   中英

Django login required middleware not working

I'm new to Django and I'm trying to implement the django-login-required-middleware in my project to be able to direct all the users who are not logged in to the index page with login view.

I Installed the pip install django-login-required-middleware , added login_required in my INSTALLED_APPS settings and added login_required.middleware.LoginRequiredMiddleware in my MIDDLEWARE. Then in my settings I ignore the views that I want to display to users even when They're not logged in.

settings.py

LOGIN_REQUIRED_IGNORE_VIEW_NAMES = [
    'index',
    'register'
]

However, when I run the server, I get the error

Not Found: /accounts/login/ [22/Jan/2020 12:27:56] "GET /accounts/login/?next=/ HTTP/1.1" 404 4417

and in my browser:

Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/

It seems like it automatically directs me to the accounts, even though my app is called movies_app and not accounts. Anyone knows how to fix this? Thank you very much!

urls.py

from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import editprofile

from . import views

app_name = 'movies_app'

urlpatterns = [
    path('', views.login, name='login'),
    path('browse/', views.index, name='index'),
    path('register/', views.register, name='register'),
    path('movies/', views.allMovies, name='allMovies'),
    path('movies/<int:pk>/', views.movie, name='movie'),
    path('movies/<int:pk>/rate', views.addRating, name='rate'),
    path('my-list/', views.myMovies, name='my-list'),
    path('my-list/<int:pk>/delete', views.deleteFavoriteMovie, name='favorite-movie-delete'),
    path('profile/', views.profile, name='register'),
    path('editprofile/', views.editprofile, name='editprofile'),
    path('logout/', views.logout, name='logout'),
    path('movie-video', views.movieVideo, name='movie-video')
]  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Your middleware is working and redirecting you to the default login page, /accounts/login/ .

To customise the default login page, add LOGIN_URL to your settings, eg

LOGIN_URL = '/login/'

Finally, you have app_name = 'movies_app', so you should include this when referring to URL patterns from this app. For example, your app_name = 'movies_app', so you should include this when referring to URL patterns from this app. For example, your LOGIN_REQUIRED_IGNORE_VIEW_NAMES` should be:

LOGIN_REQUIRED_IGNORE_VIEW_NAMES = [
     'movies_app:index',
     'movies_app:register'
]

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