Efraín
Efraín

Reputation: 505

How to handle different POST request on class-based-view?

i'm working with Django, and until now i have only had the necesity to make a single POST request for the page to work, but now i need to make multiple POST request, and i don't know how to handle a different POST request with the same method.

Maybe i'm not explaining me very well.

I have a view.py like

class List(View):
    def post(self, request):
        #Receive the JSON
        return JsonResponse(data,safe=False) #data is a list of dicts []

    def get(self,request):
        return  render(request,'list.html')
list =List.as_view()

Now, with this i return information to create a list of elements, and each of them has a button that opens a modal where i want to show more information. The thing is, i could just send all the information needed with the post method i have, but i don't think is correct to send too much information with one request when not all of it could be used.

So, my idea is that the button first make a new POST request for tha data i need, and then create the modal with it. My problem is that i don't know how to handle the second request, because, in theory, if i send another request, will be handled by the post() method i have, and it doesn't return the information i need, so, how to handle the second request? Is there a way to create another method post() to handle the other request? or how do i make the post() to difference which request was made?

Update To solve this problem, i sended a value with the JSON from the JS

data: {
    csrfmiddlewaretoken : csrftoken,
    value : nemp,
    second: "second"
}

And i only had to check on the view if request.POST.has_key('second'): to decide if was the first request or the second. It's a very cehap way to do it, but it works. If someone knows another way to do this, don't doubt to say it.

Upvotes: 1

Views: 1546

Answers (1)

Anonymous
Anonymous

Reputation: 12080

You could create another view with a unique url, or basically do what you suggested. Bellow is a more clean implementation of the same thing:

class List(View):
    def post(self, request, *args, **kwargs):
        method = getattr(self, 'step_' + request.POST.get('step', ''), self.step_1)
        return method(request, *args, **kwargs)

    def step_1(self, request, *args, **kwargs):
        pass

    def step_2(self, request, *args, **kwargs):
        pass

This would execute the step_1() method by default, and step_2() when the POST parameter step is 2. You can extend it as much as you like.

Although I'm not sure that "too much data in one request" is really something you should be concerned about. Might make sense if you meant "I don't want to ask the user for too much information at once, so I want to break it into a few steps".

Upvotes: 1

Related Questions