Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make POST requests to class-based Views in Django

I have created different class-based views on Django. On the HTML i created some forms make a request with AJAX. My problem is that it gives me

Method Not Allowed (POST)

I don know if i'm doing it rigth, or if i need to modify something for it to work.

My view.py is something like this

class Landing(View):
    def get(self,request):
        if request.method == 'POST':
            if request.is_ajax():
                data = {"lat":20.586, "lon":-89.530}
                print request.POST.get('value')
                return JsonResponse(data)
    return render(request,'landing.html',{'foo':'bar'})

And i send the reques from Javascript

$(document).ready(function() {
  $('#productos').on('change', function(e) {
     //Call the POST
     e.preventDefault();
     var csrftoken = getCookie('csrftoken');
     var value = $('#productos').val();

     $.ajax({
        url: window.location.href,
        type: "POST",
        data: {
            csrfmiddlewaretoken : csrftoken,
            value : value
        },
        success : function(json) {
            console.log(json);
            drop(json);
        },
        error : function(xhr,errmsg,err){
            console.log(xhr.status+": "+xhr.responseText)
        }
     });
  });
});

I got some of the code from a web, but i really don't know how to use it, since they used it without class-based views.

So, What does need my code to accept the POST method?

like image 396
Efraín Avatar asked Feb 05 '23 00:02

Efraín


1 Answers

The dispatch method of a class based view determines which function is called, so far you've written a get function, but no post function so just move the logic into a post function.

class Landing(View):
    def post(self,request):
        if request.is_ajax():
            data = {"lat":20.586, "lon":-89.530}
            print request.POST.get('value')
            return JsonResponse(data)

    def get(self, request):
         return render(request,'landing.html',{'foo':'bar'})
like image 129
Sayse Avatar answered Feb 07 '23 17:02

Sayse