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')
That’s exactly what it was, thank you!
– Juliana Marques