Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: AttributeError form has no attribute 'is_valid'

Tags:

python

django

I'm having an issue saving comments for a blog app I'm writing in Django. The error is: AttributeError at /blog/123456/ 'comment' object has no attribute 'is_valid'

My models.py:

from django.db import models

class comment(models.Model):
    comID = models.CharField(max_length=10, primary_key=True)
    postID = models.ForeignKey(post)
    user = models.CharField(max_length=100)
    comment = models.TextField()
    pub_date = models.DateTimeField(auto_now=True)

views.py:

from django.http import HttpResponse
from django.shortcuts import render
from django.template import RequestContext, loader
from django.db.models import Count
from blog.models import post, comment
from site.helpers import helpers

def detail(request, post_id):
    if request.method == 'POST':
        form = comment(request.POST) 
        if form.is_valid():
            com = form.save(commit=False)
            com.postID = post_id
            com.comID = helpers.id_generator()
            com.user = request.user.username
            com.save()
            return HttpResponseRedirect('/blog/'+post_id+"/")
    else:
        blog_post = post.objects.get(postID__exact=post_id)
        comments = comment.objects.filter(postID__exact=post_id)
        form = comment()
        context = RequestContext(request, {
            'post': blog_post,
            'comments': comments,
            'form': form,
        })
        return render(request, 'blog/post.html', context)

I'm not sure what the issue is, from the tutorials/examples I've been looking at, form should have the attribute is_valid(). Could someone help me understand what I'm doing wrong?

like image 737
Jeremy Avatar asked Sep 15 '25 06:09

Jeremy


1 Answers

comment is a Model. is_valid method are present in forms. I think what you wnat to do is create a ModelForm for comment like this:

from django import forms
from blog.models import comment

class CommentForm(forms.ModelForm):        
    class Meta:
        model=comment

And use CommentForm as IO interface to comment class.

You can learn more about ModelForms at the docs

Hope this helps!

like image 114
Paulo Bu Avatar answered Sep 17 '25 21:09

Paulo Bu