marcelo.delta
marcelo.delta

Reputation: 3082

Django form the cleaned_data field is None

Django form the cleaned_data field is None.

This field has not passed the validation.

I want to change the value of this field.

Is there another way to get the non-valid fields?

def clean(self):
    cleaned_data = super(Form, self).clean()

    print(cleaned_data.get('info')) <---- It is None

    return cleaned_data

Upvotes: 3

Views: 2641

Answers (2)

Петр Сачек
Петр Сачек

Reputation: 29

def content_view(request):
 if request.method == 'POST':
    form = ContentForm(request.POST)
    if form.is_valid():
        context = {}
        choice = form.cleaned_data['choice']

        if form.cleaned_data['upload'] == None:
            upload = 'файл не загружен'
        else:
            file = request.FILES['upload']
            upload = file.read()

        context['choice'] = choice
        context['upload'] = upload
        return render(request, 'bot/content_result.html', context)
 else:
    form = ContentForm()
 return render(request, 'bot/content_view.html', {'form': form})

Upvotes: 0

codeandfire
codeandfire

Reputation: 465

If cleaned_data is None, it should be because your existing form fields have not been validated or there is no data in them.

You can try something like this:

class Form1(forms.Form):
    # Your fields here

    def clean(self):
        if self.is_valid():    
             return super(forms.Form, self).clean() # Returns cleaned_data
        else:
             raise ValidationError(...)

EDIT: Taking note of what @Alasdair said - the following approach is better:

You could consider changing the value of 'info' beforehand, i.e. in the view, like so, instead of overriding the form's clean() method:

# In the view
data = request.POST.dict()
data['info'] = # your modifications here
form = Form1(data)
if form.is_valid():
     ... 

Upvotes: 3

Related Questions