【问题标题】:Django Create Multiple URLs that call same View for POST and GETDjango 创建多个 URL,为 POST 和 GET 调用相同的视图
【发布时间】:2016-10-26 00:14:26
【问题描述】:

我正在使用 URLconfig。我可以创建两个调用相同视图的 URL(用于 POST 和 GET)吗?

url(r'^persons/(?P<id_person>P\.\d+)/forms/(?P<formacronym>\w+)/$', views.PersonFormView.as_view()),
url(r'^persons/(?P<id_person>P\.\d+)/forms/(?P<id_form>[\w.]+)/$', views.PersonFormView.as_view())

恭敬地在视图中调用这些方法:

def get(self, request, id_person, formacronym, format = None):
    form = Form.get_form_for_person(self, id_person, formacronym)

def post(self, request, id_person, id_form, format = None):        
    form = Form.save_form(self, id_person, id_form)

现在的设置方式不起作用。不知道如何进行。感谢您的任何提示。

【问题讨论】:

    标签: python django django-views django-urls django-class-based-views


    【解决方案1】:

    如果您使用CBV,您可以构建一个指向您的视图的URL。然后根据请求方法执行相应的类方法。

    from django.views.generic import View
    
    class FooView(View):
    
        def get(self, request, *args, **kwargs):
            # only gets called when request.method == "GET"
            assert(request.method == "GET") # True
    
        def post(self, request, *args, **kwargs):
            # only gets called when request.method == "POST"
            assert(request.method == "POST") # True
    

    【讨论】:

      猜你喜欢
      • 2017-10-25
      • 1970-01-01
      • 2014-08-08
      • 2016-04-26
      • 2012-11-14
      • 2013-01-13
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      相关资源
      最近更新 更多