【问题标题】:Getting "This field is required" even though file is uploaded即使文件已上传,也获取“此字段是必需的”
【发布时间】:2013-05-06 17:19:06
【问题描述】:

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

【问题讨论】:

    标签: django forms file-upload


    【解决方案1】:

    添加 enctype="multipart/form-data"

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

    【讨论】:

      【解决方案2】:

      由于您还没有发表您的观点,我只能猜测是因为您忘记包含request.FILES

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

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

      【讨论】:

      • 抱歉,在原问题中添加了视图
      • 我已添加,但仍收到此字段为必填项
      猜你喜欢
      • 2021-02-24
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多