如何使Django中的FileField可选?
我在Django中有一个表单,里面有一个文本框和一个文件上传的地方。用户可以选择把文本粘贴到文本框里,或者上传一个文件。如果用户已经把文本粘贴到文本框里,我就不需要检查文件上传的部分了。
我该怎么让这个 forms.FileField()
变成可选的呢?
2 个回答
0
如果你想在用户提交表单之前进行一些操作,你需要使用JavaScript(比如jQuery、mootools等,这些都提供了一些快速的方法)。
在Django这边,你可以在表单里使用一个叫做“clean”的方法来处理。这会帮助你开始处理数据,并且你需要在模板上显示那些验证错误,让用户能够看到。这个“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 %}
58
如果你在一个继承自 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(也就是模型)。