2

I tried to create a profile image upload field by:

class SignUpForm(forms.Form):
    username = forms.CharField(max_length=30, \
        error_messages = {'required': 'Need a username'})
    email = forms.EmailField(max_length=30, \
        error_messages = {'required': 'Need an email', 'invalid': 'Email is invalid'})
    profile_image = forms.ImageField(error_messages = {'required': 'Please select a profile image'})

and load data in views.py:

  if request.method != 'POST':
    return HttpResponseServerError("Only POST requests allowed.")
  form = SignUpForm(request.POST, request.FILES)
  logger.info(request.FILES) # this always prints empty '{}'

the form is:

form(enctype="multipart/form-data", method='post')
      label(for='username') Username
      input#name(name='username', type='text')
      label(for='email') Email
      input#email(name='email', type='email')
      label(for='profile_image') Profile Image
      input#profile_image(name='profile_image', type='file')

the way I submit the data is in js:

$('form').submit(function(e){
  e.preventDefault();
  $("#signup-errors").hide();
  var form = $(e.target);
  var post = $.post('/user/create/', form.serialize(), redirectIfSuccess);
  post.fail(function(xhr, ajaxOptions, thrownError) {
    $("#signup-errors").html(xhr.getResponseHeader("errors")).show();
  });
});

Can someone please hint me what might be wrong? I've searched and followed the steps but the files are never posted thru... :(

thanks!

Frost
  • 3,786
  • 5
  • 23
  • 29

1 Answers1

2

Based on your update, the problem is that you're using AJAX.

Uploading files asynchronously isn't "easy". It's supported with HTLM5 but not all browsers - you definitely can't rely on this method yet.

How can I upload files asynchronously?

They way I recommend to make this work is to look at some ajax file upload plugins (which use iframes or flash) and use their API to do your POST.

http://blueimp.github.io/jQuery-File-Upload/

Community
  • 1
  • 1
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245