我在为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()
。有人能帮我理解我做错了吗?
答案 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接口。
您可以详细了解ModelForm
s at the docs
希望这有帮助!