def post_detail(request, post_id): """ Статья детально """ # добавление комментария if request.method == 'POST': form = BlogCommentForm(request.POST) if form.is_valid(): form.save(post_id) return redirect(request.path) else: form = BlogCommentForm() # загружаем статью try: # вместо get_object_or_404 применён метод get, чтобы можно было одним запросом загрузить все теги статьи post = BlogPost.objects.prefetch_related('tags').get(pk=post_id) comments = BlogComment.objects.filter(post=post, is_active=True).order_by('-create_date') # загружаем первые 10 тегов tags = BlogTag.objects.filter(is_active=True).order_by('title')[:10] except BlogPost.DoesNotExist: raise Http404() return render(request, 'blogpost/detail.html', { 'post': post, 'comments': comments, 'tags': tags, 'form': form, })
def diary(request): comment_instance = BlogComment(ip=request.META.get('HTTP_X_REAL_IP',request.META['REMOTE_ADDR']),name=request.COOKIES.get('comment_name',None)) comment_form = BlogCommentForm(instance=comment_instance, data=request.POST if request.method == "POST" and 'submit_comment' in request.POST else None) if request.method == "POST" and 'submit_comment' in request.POST and comment_form.is_valid(): comment_instance.blog = Blog.objects.get(id=int(request.POST['blog_id'])) comment = comment_form.save() messages.success(request, _("Comment added")) response = HttpResponseRedirect('/diary/') response.set_cookie('comment_name', value=comment_form.cleaned_data['name'].encode("UTF-8"), max_age=60*60*24*100) return response context = { 'blogs': Blog.objects.filter(display=True).order_by('-date') , 'comment_form': comment_form } return HttpResponse(loader.get_template("blog.html").render(RequestContext(request,context)))
def post_comment(request, src): # 先获取被评论的文章,因为后面需要把评论和被评论的文章关联起来。 # 这里我们使用了 Django 提供的一个快捷函数 get_object_or_404, # 这个函数的作用是当获取的文章(article_list)存在时,则获取;否则返回 404 页面给用户。 paper = get_object_or_404(article_list, src=src) # HTTP 请求有 get 和 post 两种,一般用户通过表单提交数据都是通过 post 请求, # 因此只有当用户的请求为 post 时才需要处理表单数据。 if request.method == 'POST': # 用户提交的数据存在 request.POST 中,这是一个类字典对象。 # 我们利用这些数据构造了 BlogCommentForm 的实例,这样 Django 的表单就生成了。 form = BlogCommentForm(request.POST) # 当调用 form.is_valid() 方法时,Django 自动帮我们检查表单的数据是否符合格式要求。 if form.is_valid(): # 检查到数据是合法的,调用表单的 save 方法保存数据到数据库, # commit=False 的作用是仅仅利用表单的数据生成 Comment 模型类的实例,但还不保存评论数据到数据库。 comment = form.save(commit=False) # 将评论和被评论的文章关联起来。 comment.article = paper # 最终将评论数据保存进数据库,调用模型实例的 save 方法 comment.save() # 重定向到 post 的详情页,实际上当 redirect 函数接收一个模型的实例时,它会调用这个模型实例的 get_absolute_url 方法, # 然后重定向到 get_absolute_url 方法返回的 URL。 return HttpResponseRedirect("/article/" + src + "/") else: # 检查到数据不合法,重新渲染详情页,并且渲染表单的错误。 # 因此我们传了三个模板变量给 article.html, # 一个是文章(Post),一个是评论列表,一个是表单 form # 注意这里我们用到了 post.comment_set.all() 方法, # 这个用法有点类似于 Post.objects.all() # 其作用是获取这篇 post 下的的全部评论, # 因为 Post 和 Comment 是 ForeignKey 关联的, # 因此使用 post.comment_set.all() 反向查询全部评论。 comment_list = paper.blogcomment_set.all() context = {'post': paper, 'form': form, 'comment_list': comment_list } return render(request, 'article.html', context=context) # 不是 post 请求,说明用户没有提交数据,重定向到文章详情页。 return render(request,"article.html",locals())