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);
}
});
});
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
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.