Zain Khan
Zain Khan

Reputation: 3793

File field not passing data to form

I am using python 2.7 & django 1.5

Forms.py

class FileUploadForm( forms.Form ):
    file = forms.FileField()
    title = forms.CharField(max_length = 200)

HTML

<form action="{% url 'upload_file' %}" method="post" class="userFroms">
    {% csrf_token %}
      <ul class="pull-left">
      <li>
      <div class="formLabel ">Title</div>

      <div class="formFields"><input name="title" type="text" />

      </div>

      </li>

      <li>
      <div class="formLabel">Upload File</div>
      <div class="formFields">
     <input name="file" type="file" size="20" />
      </div>
      </li>


      </ul>
       <p align="center" style="margin:20px 0; "><input type="submit" value="submit" class="btn btn-info" /></p>

   </form>   

View.py

def upload_file(request):
    if request.method == 'POST':
        form = FileUploadForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/success/url/')
    else:
        form = FileUploadForm()
    return render_to_response('upload.html', {'form': form})


def handle_uploaded_file(f):
    with open('documents/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

My form has two fields and both are required. Therefore, when I submit the form, it checks for the validity using the form.is_valid() function. In my forms dictionary I can see that the title is being sent in cleaned_data, but the file is missing. File though is available in the dictionary. What am I doing wrong?

{'files': {}, 'is_bound': True, 'cleaned_data': {'title': u'dsad'}, 'error_class': <class 'django.forms.util.ErrorList'>, 'empty_permitted': False, 'fields': {'title': <django.forms.fields.CharField object at 0x7f64783ed410>}, 'initial': {}, 'label_suffix': u':', 'prefix': None, '_changed_data': None, 'data': <QueryDict: {u'title': [u'dsad'], u'csrfmiddlewaretoken': [u'fRCrB7JrXIQVVfQSJW70eayu5DM9PiIM'], u'file': [u'406123_138447936269777_246495737_n.jpg']}>, '_errors': {'file': [u'This field is required.']}, 'auto_id': u'id_%s'}

Upvotes: 1

Views: 2366

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599550

You haven't set the form's encoding type:

<form enctype="multipart/form-data" action="{% url 'upload_document' %}" method="post" class="userFroms">

Upvotes: 7

Related Questions