我有一个允许用户上传文本和文件的表单。但是,即使用户不上传文件(文件是可选的),我也想让它有效。但是,在 Django 中,它不允许我通过“clean(self)”。我只想简单一点——如果是文本框,则通过。如果没有文本,返回错误。
class PieceForm(forms.Form):
text = forms.CharField(max_length=600)
file = forms.FileField()
def clean(self):
cleaned_data = self.cleaned_data
text = cleaned_data.get('text')
file = cleaned_data.get('file')
return cleaned_data
在我看来...
form = PieceForm(request.POST, request.FILES)
if form.is_valid():
print 'It's valid!' ........this only prints if there is a file!
请您参考如下方法:
您必须为 the documentation 中注明的可选字段设置 required=False
在您的情况下,以下行应该可以解决问题:
file = forms.FileField(required=False)
