Django 创建多个 URL,为 POST 和 GET 调用相同的视图
Posted
技术标签:
【中文标题】Django 创建多个 URL,为 POST 和 GET 调用相同的视图【英文标题】:Django Create Multiple URLs that call same View for POST and 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)
现在的设置方式不起作用。不知道如何进行。感谢您的任何提示。
【问题讨论】:
【参考方案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
【讨论】:
以上是关于Django 创建多个 URL,为 POST 和 GET 调用相同的视图的主要内容,如果未能解决你的问题,请参考以下文章