简体   繁体   English

django decorator检查用户是否登录,否则重定向

[英]django decorator check if user is logged in otherwise redirect

if not request.user.is_authenticated():
    return HttpResponseRedirect(reverse('login_user'))

since i was doing the above, in most of my views I figured there should be something better then putting that piece in all my views. 自从我进行上述操作以来,在我的大多数意见中,我认为应该有比将其纳入我所有观点的更好的方法。

now i found something about decoraters that seems to do a bit what i want: 现在我发现了一些关于decorater的东西,似乎可以满足我的要求:

from django.views.decorators.http import require_http_methods

@require_http_methods(["GET", "POST"])
def my_view(request):

Now i wondered is this indeed done with decorators and if so how can i translate that to check if a user is logged in and redirect otherwise? 现在我想知道这确实是用装饰器完成的,如果可以的话,我该如何翻译以检查用户是否登录,否则重定向?

You can use built-in decorator: 您可以使用内置装饰器:

from django.contrib.auth.decorators import login_required

@login_required
def edit_user_profile(request):
    //some code

django login_required decorator django login_required装饰器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM