gpt4 book ai didi

python - Django 无法在数据库中保存表单

转载 作者:太空宇宙 更新时间:2023-11-03 11:24:52 25 4
gpt4 key购买 nike

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

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

表格.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',)

View .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,我也得到了输入的数据,但是表格没有被保存...非常感谢任何帮助

最佳答案

我认为问题在于您的表单排除了 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(),使您的代码更具可读性可以避免其他人的困惑。

关于python - Django 无法在数据库中保存表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36045610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com