Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使django中的FileField成为可选的?_Python_Django_Django Forms - Fatal编程技术网

Python 如何使django中的FileField成为可选的?

Python 如何使django中的FileField成为可选的?,python,django,django-forms,Python,Django,Django Forms,我有一个带有django文本框和文件字段的表单。它应该允许用户将文本粘贴到该框中或上载文件。如果用户已将文本粘贴到框中,则无需选中文件字段 如何使forms.FileField()成为可选的?如果在forms.Form派生类中使用forms.FileField(),则可以设置: class form(forms.Form): file = forms.FileField(required=False) 如果您使用的是models.FileField()并将forms.ModelForm

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


如何使forms.FileField()成为可选的?

如果在
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(即模型)。

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

在django方面,您可以在表单中的干净方法中执行此操作。这应该让您开始,您需要在模板上显示这些验证错误,以便用户查看。clean方法的名称必须与前缀为“clean_u3;”的表单字段名称匹配

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 %}

我在一些地方读到过
CharField
s不应该有
null=True
。。。既然
FileField
s本质上是
CharField
s,那么这真的是正确的方法吗?不要在
FileField
s上执行
null=True
。只要
blank=True
就足够了。正如@DMactheDestroyer所说,它存储为
字符域
,因此
null=True
会混淆它(其他值将存储为
null
,其他值存储为
(空字符串)。