obautista obautista - 5 months ago 31
Python Question

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

I am using URLconfig. Can I create two URLs (for POST and GET) that call same View?

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())


Would call these methods in the View respectfully:

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)


The way this is setup now is not working. Not sure how to proceed. Thanks for any tips.

Answer

If you are using CBV, you can construct one URL that points to your View. Then depending on the request method the appropriate method on the class will be executed.

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