Home > Back-end >  Why am I getting an error that my model form object has no attribute 'cleaned_data'?
Why am I getting an error that my model form object has no attribute 'cleaned_data'?

Time:07-31

I have a form on a page that users use to write comments. There is a view (comment) that should take in the users inputs along with some other information and save it to a model. However, when I tested it out, I got the error:

'CommentForm' object has no attribute 'cleaned_data'

How do I fix this?

views.py:

def comment(request, id):
    if request.method == 'POST':
        form = CommentForm(request.POST) # the form
        if form.is_valid:
            current = get_object_or_404(Listing, id=id)
            user = User.objects.get(pk=request.user.id)
            obj = Comment() # the model
            obj.user = user
            obj.listing = current
            obj.date = datetime.datetime.now()
            obj.title = form.cleaned_data['title'] # this is where the error occurs
            obj.comment = form.cleaned_data['comment']
            obj.rating = form.cleaned_data['rating']
            obj.save()
            return listing(request, current.id, current.name) 

html:

<form action=" {% url 'comment' listing.id %} " method="post" >
    {% csrf_token %}
    <h2>Comment</h2>
    {{ commentForm.title }}
    {{ commentForm.comment }}
    {{ commentForm.rating }}
    <input type="submit" value="Comment" >
</form>

forms.py:

class CommentForm(forms.Form):
    title = forms.CharField(max_length=60, widget=forms.TextInput(attrs={
        'class': 'comment-title',
        'placeholder': 'Title',
    }))
    comment = forms.CharField(max_length=1000, widget=forms.Textarea(attrs={
        'class': 'comment',
        'placeholder': 'Enter Comment'
    }))
    rating = forms.FloatField(min_value=0, max_value=5, widget=forms.NumberInput(attrs={
        'class': 'rating',
        'placeholder': 'Rating'
    }))

CodePudding user response:

What you wrote:

if form.is_valid:

What you should have written:

if form.is_valid():

Please check your code thoroughly before asking a question.

  • Related