我目前正在Django-Central网站上关注Django-Blog教程,并且正在尝试将评论部分添加到博客中。我已经显示了评论,但是似乎无法显示该表单,以便网站访问者可以在博客文章中添加评论。
views.py
package com.concretepage.security;from django.shortcuts import render, get_object_or_404 from django.views import generic from .models import Post from .forms import CommentForm # Create your views here. class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) # Fetching the comments that have active=True comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': 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() print('Comments:', comments) return render(request, template_name, {'post': post, 'comments': new_comment, 'new_comment': new_comment, 'comment_form': comment_form})
forms.py
from .models import Comment
from django import forms
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'email', 'body')
post_detail.html
package com.concretepage;<div class="col-md-8 card mb-4 mt-3"> <div class="card-body"> <!-- comments --> <h2>{{ post.comments.count }} comments</h2> {% for comment in post.comments.all %} <div class="comments" style="padding: 10px;"> <p class="font-weight-bold"> {{ comment.name }} <span class=""> {{ comment.created_on }} </span> </p> {{ comment.body | linebreaks }} </div> {% endfor %} </div> <div class="card-body"> {% if new_comment %} <div class="alert alert-success" role="alert"> Your comment is awaiting moderation </div> {% else %} <h3>Leave a comment</h3> <form method="post" style="margin-top: 1.3em;"> {% csrf_token %} {{ comment_form.as_p }} <button type="submit" class="btn btn-primary btn-lg">Submit</button> </form> {% endif %} </div> </div>
真的很感谢任何输入。
答案 0 :(得分:0)
您引用了错误的模板上下文,该表单不存在,您应该使用comment_form
,这就是您在render
方法中所称的。
应为{{ comment_form.as_p }}
。