I
I
im_age2013-12-19 21:19:33
JavaScript
im_age, 2013-12-19 21:19:33

Why is post ajax request not working in Django?

Hello! Can't make a POST AJAX request in Django. At the same time, if I change $.post to $.get , everything works.

Here is the view that generates the form:

def registration(request):
    return render(request, "reg_form.html", {'form': RegistrationForm})

in JS everything is also simple:
$.post("/registration/ajax", {},
    function(data) {
        alert(data);
    })

{% csrf_token %}there is a hidden field in the form and it is generated.

View for request processing:
def test_ajax(request):
    if request.is_ajax():
        if request.method == 'POST':
            #print request.POST
            return HttpResponse("POST")
        else:
            return HttpResponse("GET")


In the console (everything on the dev server) I see the following message:
[19/Dec/2013 18:12:56] "POST /registration/ajax HTTP/1.1" 500 10961


Tell me what is the problem and how to fix it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SilentSokolov, 2013-12-19
@im_age

Of course I would like to see the full output of the error. I also advise you to take a look at this section (ajax+csrf).

D
Dmitry Astrikov, 2013-12-20
@astrikovd

When sending a POST request to a URL without a slash at the end, django will first give you a 301 status, and then redirect your request somewhere without data. As a result, you received 500 status.
If the request is made using the GET method, even after the django redirect, the data in GET is saved and, in the end, everything worked for you.
Solution - if you use APPEND_SLASH in your config, don't forget to send ajax requests to a URL with a trailing slash.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question