FileUpload在Django中不起作用

时间:2015-10-23 11:40:36

标签: django

我正在尝试在django上传文件。

它允许我在表单中添加文件并提交没有错误但没有任何内容存储。我正在使用django-crispy-forms

models.py

class Upload(models.Model):
    upload = models.FileField(upload_to='.')

views.py

class UploadsView(UpdateView):
    form_class = UploadForm
    template_name = 'upload.html'
    model = Upload

forms.py

class UploadForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UploadForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Upload
        fields = ('upload',)

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, '..', 'media')

MEDIA_URL = '/media/'

form.html

<form method="POST" action="">{% csrf_token %}
        {{ form|crispy }}
             <input class="btn btn-primary" type="submit" value="Submit" />
             <a href="/home"><button type="button" class="btn btn-danger">Cancel</button></a>
</form>

1 个答案:

答案 0 :(得分:1)

您需要更改表单标记:

<form method="POST" action="" enctype="multipart/form-data">

来自documentation

  

请注意,request.FILES只会在请求方法为POST并且发布请求的<form>具有属性enctype="multipart/form-data"时才包含数据。否则,request.FILES将为空。