В настоящее время я следую учебному пособию Django -Blog на сайте Django -Central и пытаюсь добавить раздел комментариев в блог. У меня отображаются комментарии, но я не могу отобразить форму, чтобы посетители сайта могли добавлять комментарии к сообщениям в блоге.
views.py
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
<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>
Действительно ценю любой ввод.