操作步骤:
- 创建模型保存评论内容
- 创建表单,从而可提交评论内容并对数据进行验证。
- 添加包含该表单的视图,并将最新的评论内容添加至数据库中。
- 标记帖子的详细模板,以显示评论列表和添加新评论的表单。
1. 创建模型
1.1 编辑blog应用程序的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)
1.2. 同步到数据库
(my_env) zzx@zzx:~/mysite$ python manage.py makemigrations blog
输出如下:
Migrations for 'blog':
blog/migrations/0002_comment.py
- Create model Comment
(my_env) zzx@zzx:~/mysite$ python manage.py migrate
输出如下:
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
1.3. 将新模型添加到管理站点中
from .models import Post,Comment
@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ('name','email','post','created','active')
list_filter = ('active','created','updated')
2. 创建模型中的表单
编辑blog应用程序的forms.py文件,并添加下列代码:
from .models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
针对CommentForm表单,仅需使用name、email和body字段——这些字段仅是用户可填写的字段。
3. 添加视图
编辑views.py文件,修改post_detail视图,如下所示:
from .models import Post,Comment
from .forms import EmailPostForm,CommentForm
def post_detail(request,year,month,day,post):
post = get_object_or_404(Post,slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
# List of active comments for this post
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
# A comment was posted
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request,
'blog/post/detail.html',
{'post':post,
'comments':comments,
'new_comment':new_comment,
'comment_form':comment_form})
4. 模板
使用post/detail.html模板执行下列操作:
- 显示帖子的全部评论数量
- 显示评论列表
- 向用户展示一个表单,并可添加新的评论内容
4.1 显示帖子的全部评论数量
{% with comments.count as total_comments %}
<h2>{{ total_comments }} comment{{ total_comments|pluralize }}</h2>
{% endwith %}
4.2 显示评论列表
{% for comment in comments %}
<div class="comment">
<p class="info">
Comment {{ forloop.counter }} by {{ comment.name }} on
{{ comment.created }}
</p>
{{ comment.body|linebreaks }}
</div>
{% empty %}
<p>There are no comments yet.</p>
{% endfor %}
4.3 向用户展示一个表单,并可添加新的评论内容
{% if new_comment %}
<h2>Your comment has been added.</h2>
{% else %}
<h2>Add a new comment</h2>
<form action="." method="post">
{{ comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Add comment"></p>
</form>
{% endif %}
最终效果如下: