Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

320
Views
How to make a POST request using DJANGO REST framework with ajax

This is my model class:

    class PoliceAssurance(models.Model):
        Numpolice = models.IntegerField()
        Raison = models.CharField(max_length=50)
        Tel = models.IntegerField()
        Email = models.CharField(max_length=50)

and here is my serializer:

    class PoliceSerializer(serializers.ModelSerializer):        
        class Meta:
            model = PoliceAssurance
            fields = ('Numpolice','Raison','Tel','Email');

Now, I need to make a POST request through an AJAX call. Could anyone please provide information on how I may approach this task?

this is my views.py

@login_required(login_url="login/")
def home(request):
    return render(request,"home.html")

class PoliceViewset(generics.ListCreateAPIView):    
    queryset = PoliceAssurance.objects.all()
    serializer_class =  PoliceSerializer    

and my urls.py

    urlpatterns=[
    url(r'^$', views.home, name='home'),
    url(r'PoliceAssurance',views.PoliceViewset.as_view(),              name='PoliceAssurance'),
    ]

this my ajax request

$(#suit).click(function(){          

    var data = {};
    data.Numpolice = $(#num).val();
    data.Raison = $(#raison).val();
    data.Tel = $(#tel).val();
    data.Email = $(#email).val();

    $.ajax({
        type: "POST",
        url: "/PoliceAssurance/",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data){
            alert(data);
        },
        failure: function(errMsg) {
            alert(errMsg);
        }
    });
});
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

you may need to see this, http://www.django-rest-framework.org/topics/ajax-csrf-cors/#javascript-clients and django docs in this link(detail), and my code works for me well likes

$.ajax({
    url: 'your web url',
    type: 'POST',
    beforeSend: function (xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
    },
    success: function (arg) {
        location.reload()
    }
})

Django rest framework not works like normal django. You need to trans "csrfmiddlewaretoken" in data to "X-CSRFToken" or "HTTP-X-CSRFToken" in RequestHeader

over 4 years ago · Santiago Trujillo Report

0

You need to send the CSRF information along with the Ajax request probably, or exempt your view. See here. If you include this beforeSend function in your ajax it can do the trick:

    $.ajax({
          type: "POST",
          ...
          beforeSend: function(xhr, settings) {
                  if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                          xhr.setRequestHeader("X-CSRFToken", {% csrf_token %});
               }
          },
          ...

Assuming the javascript is part of a template, the csrftoken can be optained by {% csrf_token %}.

Hope this helps.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!