如何将评论链接到django中的单个帖子?

时间:2017-04-15 03:33:54

标签: python django views

我有一个问题,我想帮助我解决。 我有一个" Post"包括评论但是,当我评论" Post"我在" Post 1"出现在" Post 2"在所有"帖子"我想将评论链接到一个帖子,我一直在寻找解决方案,但我无法使其发挥作用。

编辑我添加了 post / models.py
class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='cooments')
    user = models.ForeignKey(User, unique=False)
    text = models.CharField(max_length=250)
    created_date = models.DateTimeField(default=timezone.now)
    approved_comment = models.BooleanField(default=False)

models.py

@login_required
def add_comment_to_post(request, pk):
   post= get_object_or_404(Post, pk=pk)
   if request.method == 'POST':
       form = CommentForm(request.POST)
       if form.is_valid():
          comment = form.save(commit=False)
          comment.post= post
          comment.user = request.user
          comment.save()
          return redirect('post_detail', slug=post.slug)
   else:
       form = CommentForm()
   return render(request, 'comments/add_comment_to_post.html', {'form':form})

views.py

<form action="{% url 'add_comment_to_post' pk=post.pk %}" method="post">
  {% csrf_token %}
  {{form.as_p}}
  <input type="submit" class="btn btn-primary" value="Comentar">
</form>

我的 add_comment.html ,此代码片段包含在我的 post_detail.html

  <div class="container">
  <div class="row">
  <div class="col-md-6 comment" style="text-align: center;">

    <!-- HERE IS WHERE I INCLUDE THE add_comment.html -->

    {% include 'comments/add_comment_to_post.html' %}
  </div>
{% for comment in comments %}
{% if user.is_authenticated or comment.approved_comment %}
    <div class="col-sm-6 col-sm-offset-1">
      <div class="media-body">
          <div class="well well-lg">
            <div class="avatar">
              <img src="{{comment.user.profile.pic.thumbnail.url}}" class="img-responsive img-circle" alt="">
            </div>
              <h4 class="media-heading text-uppercase reviews">{{comment.user.get_full_name}} </h4>
              <ul class="media-date text-uppercase reviews list-inline">
                <li>{{comment.created_date}}</li>
              </ul>
              <p class="media-comment">
                  {{comment.text}}
              </p>
              <a class="btn btn-info btn-circle text-uppercase" href="#" id="reply"><span class="glyphicon glyphicon-share-alt"></span> Reply</a>
              <a class="btn btn-warning btn-circle text-uppercase" data-toggle="collapse" href="#replyOne"><span class="glyphicon glyphicon-comment"></span> 2 comments</a>
          </div>
      </div>
    </div>
{% endif %}
{% empty %}
  <p>No hay comentarios que mostrar :(</p>
{% endfor %}
  </div>
</div>

我的 book_detail.html

if (isNaN(noun) === true) {
}
....

知道如何让评论有效吗?谢谢!

1 个答案:

答案 0 :(得分:1)

在评论模型中尝试删除unique = False

更改

class Comment(models.Model):
   user = models.ForeignKey(User, unique=False)

class Comment(models.Model):
    user = models.ForeignKey(User) # remove unique=False

执行上述操作并从那里取出