【问题标题】:How to make FileField in django optional?如何使 django 中的 FileField 成为可选的?
【发布时间】:2011-08-21 20:52:59
【问题描述】:

我在 django 中有一个带有文本框和文件字段的表单。它应该允许用户将文本粘贴到该框中或上传文件。如果用户已将文本粘贴到框中,则无需检查 fileField。

如何使 forms.FileField() 可选?

【问题讨论】:

    标签: python django django-forms


    【解决方案1】:

    如果您在forms.Form 派生类中使用forms.FileField(),您可以设置:

    class form(forms.Form):
        file = forms.FileField(required=False)
    

    如果您使用的是 models.FileField() 并为该模型分配了 forms.ModelForm,则可以使用

    class amodel(models.Model):
        file = models.FileField(blank=True, null=True)
    

    您使用哪一个取决于您如何派生表单以及您是否使用底层 ORM(即模型)。

    【讨论】:

    • 我在CharFields 不应该有null=True...的地方读到了,因为FileFields 本质上是CharFields,这真的是要走的路吗?
    • 不要在FileFields 上做null=True。只需blank=True 就足够了。正如@DMactheDestroyer 所说,它存储为CharField,因此null=True 会混淆它(其他值将存储为NULL,其他值将存储为""(空字符串)。
    【解决方案2】:

    如果您想在用户提交表单之前执行此操作,则需要使用 javascript(jquery、mootools 等都提供一些快速方法)

    在 django 方面,您可以在表单中以干净的方法执行此操作。这应该可以帮助您入门,并且您需要在模板上显示这些验证错误,以供用户查看。 clean 方法的名称必须与前面带有“clean_”的表单字段名称匹配。

    def clean_textBoxFieldName(self):
      textInput = self.cleaned_data.get('textBoxFieldName')
      fileInput = self.cleaned_data.get('fileFieldName')
    
      if not textInput and not fileInput:
        raise ValidationError("You must use the file input box if not entering the full path.")
      return textInput  
    
    def clean_fileFieldName(self):
      fileInput = self.cleaned_data.get('fileFieldName')
      textInput = self.cleaned_data.get('textBoxFieldName')
      if not fileInput and not textInput:
        raise ValidationError("You must provide the file input if not entering the full path")
      return fileInput
    

    在模板上

    {% if form.errors %}
      {{form.non_field_errors}}
      {% if not form.non_field_errors %}
        {{form.errors}}
      {% endif %}
    {% endif %}
    

    【讨论】:

      猜你喜欢
      • 2011-02-10
      • 2020-02-20
      • 1970-01-01
      • 2012-08-09
      • 2011-09-17
      • 1970-01-01
      • 2017-01-21
      相关资源
      最近更新 更多