Monday, May 2, 2016

Re: Trying to make a POST call to a Django view

On 02.05.2016 19:01, carloratm wrote:
> hello everyone,
> I am a frontend developer studying Django, so please forgive my
> noobish question...
> I am trying to make a simple ajax call working.
>
> I have a form in a template. I would like to use that form to save an
> object into the database (asynchronously).
> On form submit event:
> * I prevent regular action
> * I serialize form data in a JSON
> * I pass that object to a view using a jquery POST
> * The view receive the JSON data
> * The view use the request.POST data to save an object into the database.
> * The view returns a message.
>
> Is that flow straightforward, or am I completely missing the goal?
>
> Now some code and the error I got.
>
> The relevant part of template:
>
> http://dpaste.com/3Z7TRPM
>
>
> And this is the error I got:
>
> http://dpaste.com/3FYMGYG
>
> I noticed that in the view the request.POST is *empty*!
> That is wrong, I suppose.
>

No that isn't. If jquery sets content-type, to application/json Django
doesn't put that data in .POST, but it's in .body

Django only puts in .POST form-data (either urlencoded or multipart)

> I am surely missing something.
> Any help is really appreciated.
>

If you want to send JSON data with ajax, using something like django-nap
or django-rest-framework is a great help.

--

Jani Tiainen

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/57283A8B.2090502%40gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment