【问题标题】:Am trying to filter through comment object of Post, but I keep getting all the comments, How do i get each separate comment to it user?我试图过滤 Post 的评论对象,但我不断收到所有评论,我如何将每个单独的评论发送给它的用户?
【发布时间】:2021-09-15 11:18:12
【问题描述】:

这是我的帖子列表视图,我希望将每个用户的评论分配给他们的帖子,但我在弄清楚如何让每个用户发表评论而不是在一个用户帖子中获得所有 cmets 时遇到了挑战?

def post_listview(request,*args,**kwargs):
    context =  {}
    cart = Cart(request)
    user_id = kwargs.get("user_id")
    user = request.user
    post_comment = Comment.objects.filter()

    if request.method == 'POST':
        form = NewCommentForm(request.POST)
        if form.is_valid():
            data = form.save(commit=False)
            data.post = post
            data.username = user
            data.save()
            return redirect('feed', pk=user_id)
    else:
        form = NewCommentForm()
    for user in Post.objects.all():
            if request.user.is_authenticated:
                friend_list = FriendList.objects.get(user=request.user )
                friends = friend_list.friends.all()

                context['friends'] = friends
    

    context['posts'] = Post.objects.all()
    context['cart'] = cart
    context['post_comment'] = post_comment
    

    return render(request,'feed/feed.html',context)

这是我的帖子列表视图的网址!

path('', views.post_listview, name="feed"),

这是我在模板中用来渲染 cmets 的模板标签

{% for comment in post_comment %}

{{ comment.body }}

{% endfor %} But it shows all the comment in one post, 
which is not the desire result i want, how best do i got about this ?

我的帖子模型

class Post(models.Model):
    description = models.CharField(max_length=5000, blank=True)
    pic = models.ImageField(upload_to='path/post/img' ,blank=True)
    date_posted = models.DateTimeField(auto_now_add=True)
    user_name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="users") 
    tags = models.CharField(max_length=100, blank=True)
    

    @property
    def pic_url(self):
        if self.pic and hasattr(self.pic, 'url'):
            return self.pic.url

    

    def __str__(self):
        return self.description

    def get_absolute_url(self):
        return reverse('feed', kwargs={'pk': self.pk})

    def get_date_posted(self):
        time = datetime.now()
        if self.date_posted.day == time.day:
            return str(time.hour - self.date_posted.hour) + " hrs"
        else:
            if self.date_posted.month == time.month:
                return str(time.day - self.date_posted.day) + "d"
            else:
                if self.date_posted.year == time.year:
                    return str(time.month - self.date_posted.month) + " months ago"
        return self.date_posted
 

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    username = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='comments', on_delete=models.CASCADE)
    body = models.CharField(max_length=5000)
    comment_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.body

class Like(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='likes', on_delete=models.CASCADE)
    post = models.ForeignKey(Post, related_name='likes', on_delete=models.CASCADE)
    like_date  = models.DateTimeField(auto_now=True)

这是我希望 cmets 成为的模板。

  {% for post in posts %}
              <div class="card lg:mx-0 uk-animation-slide-bottom-small">
      
                  <!-- post header-->
                  <div class="flex justify-between items-center lg:p-4 p-2.5">
                      <div class="flex flex-1 items-center space-x-4">
                          <a href="#">
                              <img src="{{post.user_name.profile_pic.url}}" class="bg-gray-200 border border-white rounded-full w-10 h-10">
                          </a>
                          <div class="flex-1 font-semibold capitalize">
                              <a href="#" class="text-black dark:text-gray-100"> {{ post.user_name.get_full_name }} </a>
                              <div class="text-gray-700 flex items-center space-x-2">  <span> {{ post.date_posted|timesince }}  </span> <ion-icon name="people"></ion-icon></div>
                          </div>
                      </div>
                    <div>
                      <a href="{% url 'feed:post-detail' post.id %}"> <i class="icon-feather-more-horizontal text-2xl hover:bg-gray-200 rounded-full p-2 transition -mr-1 dark:hover:bg-gray-700"></i> </a>
                      <div class="bg-white w-56 shadow-md mx-auto p-2 mt-12 rounded-md text-gray-500 hidden text-base border border-gray-100 dark:bg-gray-900 dark:text-gray-100 dark:border-gray-700" 
                      uk-drop="mode: click;pos: bottom-right;animation: uk-animation-slide-bottom-small">
                    
                          <ul class="space-y-1">
                            <li> 
                                <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md dark:hover:bg-gray-800">
                                 <i class="uil-share-alt mr-1"></i> Share
                                </a> 
                            </li>
                            <li> 
                                <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md dark:hover:bg-gray-800">
                                 <i class="uil-edit-alt mr-1"></i>  Edit Post 
                                </a> 
                            </li>
                            <li> 
                                <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md dark:hover:bg-gray-800">
                                 <i class="uil-comment-slash mr-1"></i>   Disable comments
                                </a> 
                            </li> 
                            <li> 
                                <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md dark:hover:bg-gray-800">
                                 <i class="uil-favorite mr-1"></i>  Add favorites 
                                </a> 
                            </li>
                            <li>
                              <hr class="-mx-2 my-2 dark:border-gray-800">
                            </li>
                            <li> 
                                <a href="#" class="flex items-center px-3 py-2 text-red-500 hover:bg-red-100 hover:text-red-500 rounded-md dark:hover:bg-red-600">
                                 <i class="uil-trash-alt mr-1"></i>  Delete
                                </a> 
                            </li>
                          </ul>
                      
                      </div>
                    </div>
                  </div>
                  <div class="p-3 border-b dark:border-gray-700">
                    {{ post.description }}
                   </div>
                  <div uk-lightbox>
                      <div class="grid grid-cols-2 gap-2 p-2">
      
                          <a href="{{ post.pic_url }}" class="col-span-2">  
                              <img src="{{ post.pic_url }}" alt="" class="rounded-md w-full lg:h-76 object-cover">
                          </a>
                         
                         
                      </div>
                  </div>
      
                  <div class="p-4 space-y-3"> 
                     
                      <div class="flex space-x-4 lg:font-bold">
                          <a href="{% url 'feed:post-like' %}"  id="likebtn{{ post.id }}" class="flex items-center space-x-2">
                              <div class="p-2 rounded-full  text-black lg:bg-gray-100 dark:bg-gray-600">
                                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="22" height="22" class="dark:text-gray-100">
                                      <path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z" />
                                  </svg>
                              </div>
                              <div> Like</div>
                          </a>
                          <a href="#" class="flex items-center space-x-2">
                              <div class="p-2 rounded-full  text-black lg:bg-gray-100 dark:bg-gray-600">
                                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="22" height="22" class="dark:text-gray-100">
                                      <path fill-rule="evenodd" d="M18 5v8a2 2 0 01-2 2h-5l-5 4v-4H4a2 2 0 01-2-2V5a2 2 0 012-2h12a2 2 0 012 2zM7 8H5v2h2V8zm2 0h2v2H9V8zm6 0h-2v2h2V8z" clip-rule="evenodd" />
                                  </svg>
                              </div>
                              <div> Comment</div>
                          </a>
                          <a href="#" class="flex items-center space-x-2 flex-1 justify-end">
                              <div class="p-2 rounded-full  text-black lg:bg-gray-100 dark:bg-gray-600">
                                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="22" height="22" class="dark:text-gray-100">
                                      <path d="M15 8a3 3 0 10-2.977-2.63l-4.94 2.47a3 3 0 100 4.319l4.94 2.47a3 3 0 10.895-1.789l-4.94-2.47a3.027 3.027 0 000-.74l4.94-2.47C13.456 7.68 14.19 8 15 8z" />
                                  </svg>
                              </div>
                              <div> Share</div>
                          </a>
                      </div>
                      <div class="flex items-center space-x-3 pt-2"> 
                          <div class="flex items-center">
                              <img src="{{user.profile_pic.url}}" alt="" class="w-6 h-6 rounded-full border-2 border-white dark:border-gray-900">
            
                          </div>
                          <div class="dark:text-gray-100">
                              Liked <strong> Johnson</strong> and <strong> 12 Others </strong>
                          </div>
                      </div>
      
                      <div class="border-t py-4 space-y-4 dark:border-gray-600">
                          <div class="flex">
                              <div class="w-10 h-10 rounded-full relative flex-shrink-0">
                                  <img src="{{user.profile_pic.url}}" alt="" class="absolute h-full rounded-full w-full">
                              </div>
                              <div>
                                  <div class="text-gray-700 py-2 px-3 rounded-md bg-gray-100 relative lg:ml-5 ml-2 lg:mr-12 dark:bg-gray-800 dark:text-gray-100">
                                      {% for comment in posts.username.comments.all %}
                                      <p class="leading-6">{{ comment.body }} <urna class="i uil-heart"></urna>
                                         <i class="uil-grin-tongue-wink"> </i>
                                         </p>
                                        {% endfor %}
                                      <div class="absolute w-3 h-3 top-3 -left-1 bg-gray-100 transform rotate-45 dark:bg-gray-800"></div>
                                  </div>
                                  <div class="text-sm flex items-center space-x-3 mt-2 ml-5">
                                      <a href="#" class="text-red-600"> <i class="uil-heart"></i> Love </a>
                                      <a href="#"> Replay </a>
                                      <span> 3d </span>
                                  </div>
                              </div>
                          </div>
                         
                      </div>
                      
                      <a href="#" class="hover:text-blue-600 hover:underline">  Veiw 8 more Comments </a>
      
                      <div class="bg-gray-100 rounded-full relative dark:bg-gray-800 border-t">
                          <input placeholder="Add your Comment.." class="bg-transparent max-h-10 shadow-none px-5">
                          <div class="-m-0.5 absolute bottom-0 flex items-center right-3 text-xl">
                              <a href="#">
                                  <ion-icon name="happy-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon>
                              </a>
                              <a href="#">
                                  <ion-icon name="image-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon>
                              </a>
                              <a href="#">
                                  <ion-icon name="link-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon>
                              </a> 
                          </div>
                      </div>
      
                  </div>
      
              </div> 
              {% endfor %}

【问题讨论】:

  • 分享您的评论模型。
  • 我刚刚分享了我的模型@WillemVanOnsem。

标签: django django-models django-rest-framework django-templates


【解决方案1】:

您通过以下方式访问与Post 相关的Comments:

{% for comment in post.comments.all %}
    {{ comment.body }}
{% endfor %}

您可以通过一个额外的查询(而不是每个Post 的查询)有效地获取相关的评论,其中:

context['posts'] = Post.objects<strong>.prefetch_related('comments')</strong>

【讨论】:

  • 好吧,我只是按照您的解决方案的建议做了,但它返回一个空对象。 cmets 未显示在相关帖子中。
  • @AbubakariUmarblacKrussainUma:那么对于该帖子,没有链接到给定帖子的评论。 my_post 当然应该重命名为用于您正在渲染的Post 对象的变量。
  • @AbubakariUmarblacKrussainUma:如果你这样使用{% for post in posts %}...{% endfor %},那么你使用{% for comment in post.comments.all %} ... {% endfor %}(不是my_post)。
  • 我只是这样做了,但仍然得到空的相关评论!但是如果做这样的事情( post_comment = Comment.objects.filter()) 然后 context['post_comment'] = post_comment ,我得到了所有的评论,但它与每个帖子无关。所以我想知道这个问题来自哪里?
  • @AbubakariUmarblacKrussainUma:你确定你显示的帖子 相关 cmets,所以Comments 和post 指向一个Post 你渲染的?
【解决方案2】:
{% for comment in posts.comments.all %}

{{ comment.body }}

{% endfor %}

【讨论】:

  • 感谢您提供答案。您能否编辑您的答案以包括对您的代码的解释?这将有助于未来的读者更好地理解正在发生的事情,尤其是那些刚接触该语言并难以理解这些概念的社区成员。
猜你喜欢
  • 2022-08-08
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
相关资源
最近更新 更多