【问题标题】:Forms in Django--cannot get past "cleaned_data"Django 中的表单——无法通过“cleaned_data”
【发布时间】:2009-10-10 08:44:00
【问题描述】:

我有一个允许用户上传文本和文件的表单。但是,即使用户没有上传文件,我也想让它有效(文件是可选的)。但是,在 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!

【问题讨论】:

    标签: python django


    【解决方案1】:

    您必须为the documentation 中注明的可选字段设置required=False

    在您的情况下,以下行应该可以解决问题:

        file = forms.FileField(required=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      相关资源
      最近更新 更多