django无法在数据库中保存表单

时间:2016-03-16 19:48:44

标签: python django django-forms

我正在学习django并且我尝试使用POST方法保存表单并发现它工作正常,我无法看到保存的消息数据库(表单未提交

Models.py

class Post(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField(max_length=10000)
    pub_date = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(max_length=200, unique=True)

    def __unicode__(self):
        return self.title

    def description_as_list(self):
        return self.description.split('\n')

class Comment(models.Model):
    title = models.ForeignKey(Post)
    comments = models.CharField(max_length=200)

    def __unicode__(self):
        return '%s' % (self.title)

Forms.py

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'description')

editPostedForm = modelformset_factory(Post, PostForm)

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('comments',)
        exclude = ('title',)

Views.py

def detail(request, id):
    posts = Post.objects.get(id=id)
    comments = posts.comment_set.all()
    forms = CommentForm
    if request.method == 'POST':
        form = CommentForm(request.POST, instance=posts)
        print form
        if form.is_valid():
            form.save(commit=False)
            form.save()
        else:
          print form.errors
    else:
        form = PostForm()

    return render(request, "detail_post.html", {'forms':forms,'posts': posts,'comments':comments})

为什么没有保存帖子消息。我在控制台中获得了状态代码200,我也得到了输入的数据,但表单没有保存...非常感谢任何帮助

1 个答案:

答案 0 :(得分:2)

我认为问题在于您的表单会排除title字段,但根据Comment定义需要它。您需要将title提供给评论实例,然后保存它:

def detail(request, id):
    posts = Post.objects.get(id=id)
    comments = posts.comment_set.all()
    forms = CommentForm
    if request.method == 'POST':
        form = CommentForm(request.POST,instance=posts)
        print form
        if form.is_valid():
            # create a comment instance in memory first
            comment = form.save(commit=False)
            # fill out the title field
            comment.title = posts
            comment.save()
        else:
          print form.errors
    else:
        form = PostForm()

    return render(request, "detail_post.html", {'forms':forms,'posts': posts,'comments':comments})

另外,我不知道为什么你在一个实例中使用复数形式,例如posts应该是post,因为你使用objects.get(),使你的代码更具可读性对其他人来说有点困惑。