Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom login URL in django

I am a newbie in django and I was experting different options in Django. I have created a class based view which requires user authentication to view the web page. I am using the inbuilt LoginView.

When the url pattern is specified as follows

url(r'^login/', auth_views.LoginView.as_view(),name='login'),

it is correctly redirected to login page.

But when I give

url(r'^restaurant/login/', auth_views.LoginView.as_view(),name='login'),

I get a 404 when trying to access the page that requires user authentication. But when I manually go to that url in browser, it works perfectly fine. Why is that? Shouldn't it both cases work?

like image 263
jibin mathew Avatar asked Sep 17 '25 07:09

jibin mathew


2 Answers

It sounds like you need to set LOGIN_URL in your settings:

LOGIN_URL = '/restaurant/login/'

or, it's better to use the URL pattern name, then you don't have to update your settings when you change the login URL

LOGIN_URL = 'login'
like image 154
Alasdair Avatar answered Sep 20 '25 09:09

Alasdair


Not sure if I'd fully understand your question, just try to give a stupid answer.

Django 2.1.7

  1. use namespace&url name in settings, if you have your own login view just change admin to your url namespace and name your view as 'login'
# settings.py
LOGIN_URL = 'admin:login'
  1. then the login_required decorator will direct you the correct login page.
from django.contrib.auth.decorators import login_required

@login_required()
def month_archive(request, year, month):
    production_list = Production.objects.month_archive(year, month)
    context = {'production_list': production_list}
    return TemplateResponse(request, 'production/production_list.html', context)
  1. If it's a Class Based View, add decorator to urls.py
from django.contrib.auth.decorators import login_required

urlpatterns = [
    path('', login_required(views.ProductionList.as_view()), name='production-list'),
    path('<int:year>/<int:month>/', views.month_archive, name='production-month'),
]
like image 20
C.K. Avatar answered Sep 20 '25 09:09

C.K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!