Attributeerror at /posts/add/ 'Postform' Object has no attribute 'cleaned_data'

Asked

Viewed 26 times

0

I have a Postform class with an is_valid method that validates the form fields, but it is not recognizing the cleaned_data attribute, whenever I try to add a new post this happens:

AttributeError at /posts/add/ 
'PostForm' object has no attribute 'cleaned_data'

Postform

class PostForm(forms.Form):
image = forms.ImageField(required=False)
content = forms.CharField(widget=forms.Textarea, required=False)

def is_valid(self):
    valid = True
    image = self.cleaned_data.get('image')
    content = self.cleaned_data.get('content')

    if image is None and content is None:
        self.add_error('Seu post precisa de um texto e/ou uma imagem')
        valid = False

    return valid

def add_error(self, message):
    errors = self._errors.setdefault(forms.forms.NON_FIELD_ERRORS, forms.utils.ErrorList())
    errors.append(message)

View

@login_required
def add_post(request):
    if request.method == 'POST':
    form = PostForm(request.POST, request.FILES)

    if form.is_valid():
        data_form = form.cleaned_data
        Post.objects.create(image=data_form['image'], content=data_form['content'], user=request.user)

        return redirect('index')

else:
    return redirect('index')

1 answer

2


The cleaned_data only exists after the is_valid() is called.

In your case you are about writing the method and running here:

image = self.cleaned_data.get('image')

Only at that moment you didn’t call the super still (and isn’t even calling).

class PostForm(forms.Form):
    image = forms.ImageField(required=False)
    content = forms.CharField(widget=forms.Textarea, required=False)

    def is_valid(self):
        valid = super(PostForm, self).is_valid()

        if not valid:
            return valid

        # Aqui vai o resto do seu código

After the super runs the cheaned_data can be used.

  • That’s exactly what it was, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.