评论作为应作为一个独立的应用。
注意要将评论(Comment)和表单(CommentForm)区分开。
数据库模型
from django.db import models
class Comment(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=255)
url = models.URLField(blank=True)
text = models.TextField()
created_time = models.DateTimeField(auto_now_add=True)
post = models.ForeignKey('app.Post') # 文章 Post 作为外键
def __str__(self):
return self.text[:20]
评论表单
其实就是表单的具体化,指定表单采用的模型以及字段。
用户提交数据存放在 request.POST 对象中,以此构造 CommentForm 实例。
# comments/forms.py
from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
class meta:
model = Comment # 绑定模型和字段
fields = [name, email, text, url,] # created_time、post 字段是自动获取的
评论视图
redirect 函数:可用 URL 作为参数;也可用模型实例作为参数 ,前提是该实例有 get_absolute_url 方法。
from django.shortcuts import render, get_object_or_404, redirct
from .models import Comment
from .forms import CommentForm
from app.models import Post
def post_comment(request, post_pk):
post = get_object_or_404(Post, pk=post_pk) # 获取当前文章
if request.method == 'Post':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=Flase)
comment.post = post
comment.save()
redirct(post)
else:
comment_list = post.comment_set.all()
context = {
'post': post,
'form': form,
'comment_list': comment_list,
}
render(request, 'app/detail.html', context=context)
redirct(post)
配置 URL
from django.conf.urls import url
from . import views
app_name = 'comments'
urlpatterns = [
url(r'^/comment/post/(?P<post_pk>/d+)/$', views.post_comment, name='post_comment')
]
# blog/urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('app.urls')),
url(r'', include('comments.urls')),
]
文章详情页视图
form = CommentForm()
comment_list = post.comment_set.all()
context = {
'post': post,
'form': form,
'comment_list': comment_list,
}
return render(requests, 'app/detail.html', context=context)
前端渲染
<form action="{% url 'comments:post_comment' post.pk %}" method="post" class="comment-form">
{% csrf_token %}
<div class="row">
<div class="col-md-4">
<label for="{{ form.name.id_for_label }}">名字:</label>
{{ form.name }}
{{ form.name.errors }}
</div>
<div class="col-md-4">
<label for="{{ form.email.id_for_label }}">邮箱:</label>
{{ form.email }}
{{ form.email.errors }}
</div>
<div class="col-md-4">
<label for="{{ form.url.id_for_label }}">URL:</label>
{{ form.url }}
{{ form.url.errors }}
</div>
<div class="col-md-12">
<label for="{{ form.text.id_for_label }}">评论:</label>
{{ form.text }}
{{ form.text.errors }}
<button type="submit" class="comment-btn">发表</button>
</div>
</div> <!-- row -->
</form>