2013-07-07 20 views
2

我在保存我在Django中編寫的博客應用程序的註釋的問題。錯誤是:AttributeError at /blog/123456/ 'comment' object has no attribute 'is_valid'Django:AttributeError表單沒有屬性'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()。有人能幫我理解我在做什麼錯嗎?

+2

是什麼讓你覺得'comment'是一種形式?它是一個模型對象;你從模型模塊中導入它。 –

+0

@MartijnPieters哦,我現在覺得很愚蠢。我的模型創造形式的印象。感謝您指出了這一點。我現在去寫一些表格。 – Jeremy

回答

1

comment是模型。 is_valid方法存在於表單中。我想你wnat做的是創造一個評論ModelForm這樣的:

from django import forms 
from blog.models import comment 

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

而且使用CommentForm爲IO接口comment類。

您可以瞭解更多關於ModelForms at the docs

希望這有助於!

相關問題