如何从Django View函数中的另一个函数返回

时间:2018-09-09 05:51:04

标签: python django

我在views.py中有一个功能

def login(request):
   actor = LoginActor(request)
   actor.authenticated_user() # Cannot use return here, this is problematic, we need to redirect here without using a return statement

   ctx = actor.get()

   if request.method == 'POST':
      ctx = actor.post()

      return render(request, 'user/forms/auth.jinja', ctx)
   return render(request, 'user/login.jinja', ctx)

authenticated_user()函数中有一个重定向,定义为:

def authenticated_user(self):
    if self.request.user and self.request.user.is_authenticated:
        return redirect('home')

如何从初始视图返回而不调用return,基本上我想返回被调用函数中有return的被调用函数 我在Django 2.1和Python 3.7中使用

3 个答案:

答案 0 :(得分:2)

您应同时保留渲染和重定向到view函数,并让实用程序函数authenticated_user仅返回布尔值:

def authenticated_user(self):
    return self.request.user and self.request.user.is_authenticated

def login(request):
   actor = LoginActor(request)
   if actor.authenticated_user():
       return redirect('home')

   ctx = actor.get()

   if request.method == 'POST':
      ctx = actor.post()

      return render(request, 'user/forms/auth.jinja', ctx)
   return render(request, 'user/login.jinja', ctx)

答案 1 :(得分:0)

Django为此具有装饰器。 例如 要仅允许登录用户查看主页,

from django.contrib.auth.decorators import login_required

@login_required(login_url='/accounts/login/')
def home(request):
    ## How home page for only registered users

您可以创建一个自定义装饰器来验证来宾(未登录)用户。 有关创建自定义装饰器的帮助,请参见https://medium.com/@MicroPyramid/custom-decorators-to-check-user-roles-and-permissions-in-django-ece6b8a98d9d

答案 2 :(得分:0)

实际上,您应该使用类而不是函数来处理请求

class LoginView(View):

    login_url = "your login url"
    path = "your path to login template"

    def get(self, request):
        if request.user.is_authenticated():
            return redirect('home')
        else:
            return render(request, self.path)

    def post(self,request):
        #treatment here
        actor = LoginActor(request)
        #I am not sure how you defined LoginActor but should return None if user is not logged in otherwise it returns a logged in user I can help you more if you provide how you defined ActorLogin()
        if actor:
             redirect('home')
        return render(request, self.path,{"error_message":"couldn't login in"})`

现在,在其他视图中添加LoginRequiredMixin,因此您不需要检查用户是否已登录,或者如果您需要除用户登录之外的其他要求,则可以使用use UserPassesTest。 有关更多详细信息,请参阅有关登录的官方文档

https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.mixins.UserPassesTestMixin