我在帖子下方有一个“添加评论”按钮,该按钮重定向到带有评论形式的URL,它可以正常工作,但是... 我希望此表格显示在帖子下方。
我尝试在post_detail.html
模板中包含带有注释表单的URL,但是收到有关表单无效的错误。当我将表单传递给PostDetail()
上下文时,它已显示,但现在可以使用。
如何将PostDetail()
与我的CommentForm()
结合使用,以在同一URL上显示?
这是我的代码的一部分:
models.py
class Comment(models.Model):
author = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
text = models.TextField()
text_html = models.TextField(editable=False)
post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
approved_comment = models.BooleanField(default=False)
def __str__(self):
return self.text
def save(self, *args, **kwargs):
self.text_html = misaka.html(self.text)
super().save(*args, **kwargs)
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = models.Comment
fields = ('text',)
views.py
class PostDetail(SelectRelatedMixin, generic.DetailView):
model = models.Post
select_related = ('user', 'group')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user__username__iexact=self.kwargs.get('username'))
...
@login_required
def add_comment_to_post(request, pk, **kwargs):
post = get_object_or_404(models.Post, pk=pk)
if request.method == 'POST':
form = forms.CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.author = request.user
comment.save()
return redirect('posts:single', username=post.user, pk=post.pk)
else:
form = forms.CommentForm()
return render(request, 'posts/comment_form.html',{'form': form})
post_detail.html
{% extends "posts/post_base.html" %}
{% block post_content %}
<div class="col-md">
{% include "posts/_post.html" %}
</div>
{% endblock %}
{% block post_post %}
{% if user.is_authenticated %}
<div class="container comments">
<!-- COMMENTS FORM IN HERE -->
<a class="btn btn-primary add-comment" id="add-comment" href="{% url 'posts:add_comment' username=post.user.username pk=post.pk %}">Add Comment</a>
{% for comment in post.comments.all %}
<div class="jumbotron comment">
<p>{{ comment.author }} <span>{{ comment.created_at }}</span></p>
<p>{{ comment.text_html|safe }}</p>
</div>
{% endfor %}
</div>
{% endif %}
{% endblock %}
我将非常感谢您至少说明了我需要采取哪些步骤才能达到所述结果。