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);
        }
    });
});
8
  • 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? stackoverflow.com/questions/20306981/… Commented Jan 3, 2017 at 17:25
  • i use jquery+reactJs+html in front end Commented Jan 3, 2017 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? Commented Jan 4, 2017 at 4:23
  • i posted the code @ChidG now i have a problem to make an ajax request to post data Commented Jan 4, 2017 at 16:59
  • 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. Commented Jan 5, 2017 at 14:09

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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()
    }
})

Comments

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 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.