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

Python 如何从Django View函数中的另一个函数返回,python,django,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 ==

我在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一起使用,您应该将渲染和重定向都保留到view函数,并让实用程序函数
authenticated\u 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)

您应该将渲染和重定向都保留到视图函数,并让实用程序函数
authenticated\u 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)
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
您可以创建自定义装饰器来验证来宾(未登录)用户。 有关创建自定义装饰器的帮助,请参阅。

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
您可以创建自定义装饰器来验证来宾(未登录)用户。
有关创建自定义装饰器的帮助,请参阅。

您应该使用类而不是函数来处理请求。事实上,您可以这样做

类登录视图(视图):

现在,您可以在其他视图中添加LoginRequiredMixin,这样您就不需要检查用户是否已登录,或者如果需要用户登录以外的其他要求,则不需要使用UserPasseTest。 有关更多详细信息,请查看有关登录的官方文档


您应该使用类而不是函数来处理请求,事实上,您可以这样做

类登录视图(视图):

现在,您可以在其他视图中添加LoginRequiredMixin,这样您就不需要检查用户是否已登录,或者如果需要用户登录以外的其他要求,则不需要使用UserPasseTest。 有关更多详细信息,请查看有关登录的官方文档