2

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);
        }
    });
});
Mamoudou Ndiaye
  • 137
  • 2
  • 3
  • 13
  • 1
    This is quite broad as is. What are you using at front-end? Do you plan on using some framework such as jquery, angular, etc? http://stackoverflow.com/questions/20306981/how-do-i-integrate-ajax-with-django-applications/28341345#28341345 – Wtower Jan 03 '17 at 17:25
  • i use jquery+reactJs+html in front end – Mamoudou Ndiaye Jan 03 '17 at 17:32
  • Do you have a view? If not, you'll need one, and a url route to go with it. If so, could you post the code? – ChidG Jan 04 '17 at 04:23
  • i posted the code @ChidG now i have a problem to make an ajax request to post data – Mamoudou Ndiaye Jan 04 '17 at 16:59
  • That looks ok, although a few things you are doing are unconventional. You'll need to be a bit more specific about what your actual problem is at this stage. It looks like your problem is on the front end? What have you tried? – ChidG Jan 05 '17 at 00:04
  • i tried this request ajax @ChidG – Mamoudou Ndiaye Jan 05 '17 at 10:31
  • 2
    And what is the problem? What happens when that ajax code is called? it is very difficult to help you if you don't actually say what the problem is. One problem I can see is that your jquery selectors are using variables which are probably undefined. Usually you would need to use `$('#suit')`. rather than `$(#suit)`, unless you have defined `#suit` as a variable, and same for your other jquery selectors. – ChidG Jan 05 '17 at 14:09
  • suit is the id of the button. if i click on the button i execute an ajax requesT, i have this error " Forbidden (403) CSRF verification failed. Request aborted." – Mamoudou Ndiaye Jan 23 '17 at 13:15

4 Answers4

6

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

Tico Tico
  • 61
  • 1
  • 3
1

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.

xenosmilus
  • 11
  • 1
0

just edit for the existing answer by Tico Tico

$.ajax({
    url: 'your web url',
    type: 'POST',
    headers: {"X-CSRFToken": "{{ csrf_token }}"},
    success: function (arg) {
        location.reload()
    }
})
NourEldin Osama
  • 137
  • 3
  • 8
0
<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script>
    $(document).ready(function(){
        var csrftoken = Cookies.get('csrftoken');

        $(".auto-submit").change(function() {
            $.post({
                url: "{% url 'get-checkin-type' %}",
                data: $(".auto-submit option:selected").val(),
                headers: {
                    X-CSRFToken: csrftoken
                }
            })
        });
    });
</script>


<form action="" method="post">{% csrf_token %}
    {% for field in form %}
        <div class="{% if field.name == 'checkin_type' %}auto-submit{% endif %}">
            {{ field.errors }}
            {{ field.label_tag }}
            {{ field }}
        </div>
    {% endfor %}
    <input type="submit" value="Send message" />
</form>
</code>
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 29 '23 at 08:23