文件字段未将数据传递给表单

时间:2013-04-03 09:25:04

标签: django django-forms django-1.5

我正在使用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)

我的表单有两个字段,都是必需的。因此,当我提交表单时,它使用form.is_valid()函数检查有效性。在我的表单字典中,我可以看到标题是在cleaning_data中发送的,但文件丢失了。文件虽然可以在字典中找到。我做错了什么?

{'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'}

1 个答案:

答案 0 :(得分:6)

您尚未设置表单的编码类型:

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