Jarana Manotumruksa
Jarana Manotumruksa

Reputation: 180

How to send django text and picture form by ajax

What I am trying to do is sending user's text with/wihtout picture and response them to a page without reload the page again.

Django form:

class PostForm(forms.ModelForm):
text = forms.CharField(max_length=128)
picture = forms.ImageField(required=False)
class Meta:
    model = Post
    fields = ['text', 'picture',]

HTML:

<form id="post_form" enctype="multipart/form-data">

   <div class="fieldWrapper">  
      {% csrf_token %}   
      {{ postForm.as_p }}
   </div>
   <INPUT id="postBtn" type="submit" name="submit" value="submit"/>
</form>

JQuery:

$("#postBtn").click(function() {
    $.ajax({
           type: "POST",
           url: "/restaurant/feed/",
           data: $("#post_form").serialize(),
           success: function(data)
           {
                // do something
           }
    })
}

Views:

def feed(request):
 print request.FILES

A result I got from print is empty list. Any suggestion? by the way I can upload picture without ajax method.

Upvotes: 3

Views: 706

Answers (1)

Hieu Nguyen
Hieu Nguyen

Reputation: 8623

You can't send files via jQuery $.ajax(), you should go for other solution then, like http://blueimp.github.io/jQuery-File-Upload/ or https://github.com/Widen/fine-uploader

Upvotes: 3

Related Questions