Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

322
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda