Django:AttributeError表单没有属性'is_valid'

时间:2013-07-07 13:18:31

标签: python django

我在为Django写的博客应用程序保存评论时遇到问题。错误是:AttributeError at /blog/123456/ 'comment' object has no attribute 'is_valid'

我的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)

我不确定问题是什么,从我一直在查看的教程/示例中,form应该具有属性is_valid()。有人能帮我理解我做错了吗?

1 个答案:

答案 0 :(得分:2)

comment是一个模型。 is_valid方法存在于表单中。我认为你要做的就是创建ModelForm这样的评论:

from django import forms
from blog.models import comment

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

并使用CommentForm作为comment类的IO接口。

您可以详细了解ModelForms at the docs

希望这有帮助!