Django 创建多个 URL,为 POST 和 GET 调用相同的视图

Django Create Multiple URLs that call same View for POST and GET

我正在使用 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())

会在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)

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

如果您正在使用 CBV,您可以构建一个指向您的视图的 URL。然后根据请求方法执行 class 上的适当方法。

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