即使文件已上载,也需要“此字段是必需的”

时间:2013-05-12 15:44:46

标签: django forms file-upload

我是Django的新手并尝试了一个简单的表格。我有一个模型类“Profile”,它定义了一个文件字段(schema_file),还有一个ModelForm类。当我尝试在浏览器中创建新的配置文件时,即使我在文件选择器中选择了一个文件,但是在schema_file字段中出现错误“此字段是必需的”,任何想法?我的课程如下:

class Profile(models.Model):
    class Meta:
        db_table = 'target_profiles'

    class SchemaType:
        XML = 1
        CSV = 2
        XLS = 3
        JSON = 4
        DB = 5
        SCHEMA_CHOICES = (
                          (XML, 'XML'),
                          (CSV, 'CSV'),
                          (XLS, 'Excel'),
                          (JSON, 'JSON'),
                          (DB, 'Database'),
                          )

    name = models.CharField(max_length=32, unique=True)
    description = models.CharField(max_length=128, null=True, blank=True)
    schema_type = models.IntegerField(choices=SchemaType.SCHEMA_CHOICES, default=SchemaType.CSV)
    schema_file = models.FileField(upload_to='schema_files', max_length=64)


    def __unicode__(self):
        return self.name

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile

视图:

def add_profile(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST, request.FILES)
        if form.is_valid():
            cd = form.cleaned_data
            return HttpResponseRedirect('/profiles')
    else:
        form = ProfileForm()
    return render(request, 'profiles/add_profile.html', {'form': form})

2 个答案:

答案 0 :(得分:38)

由于您尚未发布视图,我只能猜测它,因为您忘记包含request.FILES

form = ProfileForm(request.POST, request.FILES)

也许忘了在表单中添加enctype=multipart/form-data

答案 1 :(得分:1)

添加enctype =“ multipart / form-data”

<form enctype="multipart/form-data" method="post">
    {% csrf_token %}
    {{ form.as_p }}
<button type="submit">Upload</button>
</form>