3

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

我的模型.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)

视图.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(). 有人可以帮我理解我做错了什么吗?

4

1 回答 1

2

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

from django import forms
from blog.models import comment

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

CommentForm用作类的 IO 接口comment

您可以在文档中了解有关s 的更多信息ModelForm

希望这可以帮助!

于 2013-07-07T13:27:30.177 回答