Django区分get / post in view的方法

时间:2015-11-06 19:38:29

标签: django model-view-controller

我一直在使用其他语言,我可以只使用一个方法名称(在控制器中)进行一次操作(让我们说登录)。例如在Spring MVC中我可以有一个名为' login'并通过注释属性设置方法类型(获取或发布)。 Django有可能吗? 例如,我有这个方法登录:

def login(request):
    return render(request, 'login.html')

这个方法是通过GET加入的,我是否需要声明新方法,即login_post(request)进行帖子访问?或者我应该检查request.POST [' value']在第一种方法中是否为空,如果不是那么它是POST,如果它是空的那么它应该是GET。我是Django的新手,你的建议如何?感谢。

2 个答案:

答案 0 :(得分:3)

没有必要为每个人创建功能,你可以"问"请求:

你可以:

def login(request):
    if request.method == 'POST':
        # Your code for POST
    else:
        # Your code for GET
    return render(request, 'login.html')

或者,您可以将GET视为默认值:

def login(request):
    if request.method == 'POST':
        # Your code for POST
        # make sure to put a "return redirect" statement here
    # Your code for GET
    return render(request, 'login.html')

两个都没关系。另外,请查看Class-based Views作为替代方案,它们非常有用。

答案 1 :(得分:2)

正如Django documentation中所提到的,另一种方法是使用基于类的视图。

  

基于类的视图提供了另一种将视图实现为Python对象而非函数的方法。它们不替换基于函数的视图,但与基于函数的视图相比具有一定的差异和优势:

     
      
  • 与特定HTTP方法(GET,POST等)相关的代码组织可以通过单独的方法而不是条件分支来解决。
  •   
  • 面向对象的技术(如mixins(多重继承))可用于将代码分解为可重用的组件。
  •   

所以不要使用基于函数的视图(如其他答案中所述):

    SELECT ID, Name, Location, Type,
          SUM(CASE WHEN Active = 'Yes' THEN 1 ELSE 0 END) as [Active Count(Yes)],
          SUM(CASE WHEN Active = 'No' THEN 1 ELSE 0 END) as [Active Count(No)]

    From (Original SQL command) 
    GROUP BY ID, Name, Location, Type

您可以使用基于类的视图,如下所示:

from django.shortcuts import render

def login(request):
    if request.method == 'POST':
        # handle the post request
     else:
         # handle the get request
     return render(request, 'login.html')

使用基于类的视图时,您的urls.py将如下所示:

from django.shortcuts import render
from django.views.generic import View

class LoginView(View):
    def post(self, request):
        # handle the post request
        return render(request, 'login.html')

    def get(self, request):
        # handle the get request
        return render(request, 'template-path.html')