Django Forms - Cannot Pass "cleaned_data"

I have a form that allows users to upload text and file. However, I would like to make it valid even if the user does not upload the file (the file is optional). However, in Django, this prevents me from going through "clean (me)". I just want to keep it simple - if there is a textbox, go through. If there is no text, return an error.

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

      

In my views ...

form = PieceForm(request.POST, request.FILES)
if form.is_valid():
    print 'It valid!' ........this only prints if there is a file!

      

+2


source to share


1 answer


You have to set required=False

for fields that are optional as stated in the documentation

In your case, the following line should do the trick:



    file = forms.FileField(required=False)

      

+4


source







All Articles