15

我是 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})
4

2 回答 2

51

由于您尚未发布您的观点,我只能猜测它,因为您忘记包括request.FILES

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

也许忘了添加enctype=multipart/form-data到您的表格中。

于 2013-05-12T15:55:41.220 回答
3

添加 enctype="multipart/form-data"

<form enctype="multipart/form-data" method="post">
    {% csrf_token %}
    {{ form.as_p }}
<button type="submit">Upload</button>
</form>
于 2020-06-22T14:10:45.040 回答