How to specify the login_required redirect url in django?

DjangoDjango Views

Django Problem Overview


I have a view function:

@login_required
def myview():
    # do something
    # respond something
    pass

How can I specify the exact URL for this view function to be redirected?

Django Solutions


Solution 1 - Django

LOGIN_URL in your settings

Reference:

Solution 2 - Django

you can do this in your view works fine for me without declaring in settings.py

from django.contrib.auth.decorators import login_required

@login_required(login_url='/example url you want redirect/') #redirect when user is not logged in
def myview(request):
    do something
    return something #returns when user is logged in

Solution 3 - Django

default login url is: '/accounts/login/'
if you want to change it then go to settings.py

LOGIN_URL='/path/to/url'
LOGIN_REDIRECT_URL='/path/to/redirecturl'

Solution 4 - Django

this from documentation should be helpful: https://docs.djangoproject.com/en/1.5/topics/auth/default/#the-login-required-decorator

@login_required(login_url='/accounts/login/')
def my_view(request):
    ...

Solution 5 - Django

Go to your setting.py You can add this anywhere in your settings.py file but i prefer to place it at the bottom. LOGIN_URL = '/login/'

NOTE: '/login/' is the URL segment that brings the user to the login page. The complete URL is similar to this "myexample.com/login/".

Solution 6 - Django

In django project settings

add below code

LOGIN_REDIRECT_URL = 'path/to/url'

and then import this LOGIN_REDIRECT_URL in your views and add

`@login_required(login_url=LOGIN_REDIRECT_URL)`

to the top of your views you want to restrict it will work

Solution 7 - Django

you can also take url from view

for example

path('login/', login_view, name='login_name'),

then decoratorwill be

@login_required(login_url='login_name')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPolView Question on Stackoverflow
Solution 1 - DjangoBobView Answer on Stackoverflow
Solution 2 - DjangokartheekView Answer on Stackoverflow
Solution 3 - Djangoabe312View Answer on Stackoverflow
Solution 4 - Djangovijay shankerView Answer on Stackoverflow
Solution 5 - DjangoAmazing AngeloView Answer on Stackoverflow
Solution 6 - Django5h4d0w5View Answer on Stackoverflow
Solution 7 - DjangoNurlan JoldibaevView Answer on Stackoverflow