1.创建一个模型,用来保存评论的内容
2.创建表单,用以提交评论内容并对数据进行验证
3.添加包含表单的视图,并将内容添加到数据库中
4.标记帖子的详细模板,已显示表单
在models.py中添加模型代码
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments")
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return 'Comment by {} on {}'.format(self.name, self.post)
上述模型中包含了foreignKey,这是一种多对一的关系,每条评论由一个帖子生成,而每个帖子可包含多条评论。
新模型的迁移
makemigrations blog
migrations