开发者

How to specify the login_required redirect url in django?

I have a view function:

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

How can I specify the ex开发者_高级运维act URL for this view function to be redirected?


LOGIN_URL in your settings

Reference:

  • LOGIN_URL
  • LOGIN_REDIRECT_URL


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


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'


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):
    ...


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/".


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


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')


We have two approaches, first is the best practice for code maintenance in the future, and the second will be a hassle when the URL for login changes

First approach

in setting.py import reverse_lazy, and set LOGIN_URL to the login namespace

from django.urls import reverse_lazy
LOGIN_URL = reverse_lazy('login')

In your views, you import login_required and require login before each function

from django.contrib.auth.decorators import login_required

@login_required()
def view_name(request):
    pass

Second approach
This approach is not reliable since you won't have a defined variable holding your login URL namespace

In your views, you import login_required and require login before each function

from django.contrib.auth.decorators import login_required

@login_required(login_url='/path/to/login/')
def view_name(request):
    pass

In both cases what is static is you will have to import login_required in views

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜