Django“提交的文件是空的”

时间:2018-03-03 23:28:03

标签: django python-2.7 django-models django-forms django-views

我在模型中使用了多个FileFields,我的应用程序在执行时给出了“提交的文件为空”的错误,下面是我的代码的详细信息:

我的models.py:

class KBCTest(models.Model):
algorithm = models.CharField(max_length=10, blank=False)
entityFile = models.FileField(blank=False,
                              upload_to=updateFilename,
                              validators=[validateTestingFileExtension])
relationFile = models.FileField(blank=False,
                                upload_to=updateFilename,
                                validators=[validateTestingFileExtension])

我的forms.py

class KBCTestForm(forms.ModelForm):
class Meta:
    model = KBCTest
    fields = ('algorithm', 'entityFile', 'relationFile')

def clean(self):
    super(KBCTestForm, self).clean()
    data = self.cleaned_data
    return data

我的views.py:

def testing(request):
title = 'Testing'
template = 'testing.html'
form = ''

if request.method == 'GET':
    form = KBCTestForm()

if request.method == 'POST':
    form = KBCTestForm(request.POST, request.FILES)
    if form.is_valid():
        form.save()
        runAlgo = Run(form.cleaned_data)
        runAlgo.configAndTest()
        return HttpResponseRedirect(reverse('learning', kwargs={'function': 'testing'}))

context = {'title': title, 'form': form}
return render(request, template, context)

我的模板:

{% if request.user.is_authenticated %}
        <div class='col-sm-4 col-sm-offset-4'>
            <h1>{{ title }}</h1>
            <!-- If form not rendered(i.e. views context) don't show submit button -->
            {% if form %}
                <!-- Use 'csrf_token' to prevent cross-site forgery -->
                <form enctype='multipart/form-data' method='POST', action=''>
                    {% csrf_token %}
                    {{ form|crispy }} </br>
                    {{ form.non_field_errors|crispy }}
                <input type='submit' value='Test' class='btn btn-default'/>
                </form>
            {% endif %}
        </div>
    {% endif %}

当我运行此模板时,它无法验证表单并提供错误“提交的文件为空”错误,如下面的屏幕截图所示: Result after pressing the button

1 个答案:

答案 0 :(得分:0)

查看Django文档的this部分,其中提到allow_empty_file的参数forms.FileField。也许它会给你一些线索。

注意:我不确定这对ModelFormModel.FileField的适用方式。