4

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?

2
  • 2
    What makes you think comment is a form? It is a model object; you imported it from your models module. Commented Jul 7, 2013 at 13:19
  • @MartijnPieters Oh, I feel stupid now. I was under the impression that models create forms. Thanks for pointing that out. I'll go write some forms now. Commented Jul 7, 2013 at 13:27

1 Answer 1

3

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.