操作步驟:
- 創(chuàng)建模型保存評論內(nèi)容
- 創(chuàng)建表單掷匠,從而可提交評論內(nèi)容并對數(shù)據(jù)進(jìn)行驗(yàn)證。
- 添加包含該表單的視圖岖圈,并將最新的評論內(nèi)容添加至數(shù)據(jù)庫中讹语。
- 標(biāo)記帖子的詳細(xì)模板,以顯示評論列表和添加新評論的表單蜂科。
1. 創(chuàng)建模型
1.1 編輯blog應(yīng)用程序的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. 同步到數(shù)據(jù)庫
(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. 將新模型添加到管理站點(diǎn)中
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. 創(chuàng)建模型中的表單
編輯blog應(yīng)用程序的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模板執(zhí)行下列操作:
- 顯示帖子的全部評論數(shù)量
- 顯示評論列表
- 向用戶展示一個表單,并可添加新的評論內(nèi)容
4.1 顯示帖子的全部評論數(shù)量
{% 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 向用戶展示一個表單缓待,并可添加新的評論內(nèi)容
{% 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 %}
最終效果如下: