所有评论都链接到所有帖子

时间:2020-07-24 19:08:40

标签: python html django

我试图创建一个博客,一些用户可以在该博客上发表文章然后发表评论。 但是现在我看到我的评论已连接到所有帖子。我的意思是,当我正常单击某个帖子时,我应该只会看到对该帖子的评论,但会看到所有评论。非常感谢。

models.py

from django.db import models
from django.contrib.auth.models import User
from django.utils.text import slugify
# Create your models here.

class PostModel(models.Model):
    post = models.TextField(max_length=256, unique=True)
    slug = models.SlugField(max_length=20, unique=True)
    author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='post_author')
    created_on = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_on']

    def save(self, *args, **kwargs):
        self.slug = self.slug or slugify(self.post)
        super().save(*args, **kwargs)

    def __str__(self):
        return self.post


class CommentModel(models.Model):
    post = models.ForeignKey('dictionary.PostModel', on_delete=models.CASCADE, related_name='post_comment')
    comment=models.TextField(max_length=256,unique=True)
    author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='comment_author')
    created_on = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_on']


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


    def __str__(self):
        return self.comment

views.py

from django.shortcuts import render,redirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
from django.views.generic.edit import FormMixin
from .models import PostModel,CommentModel
from .forms import PostForm,CommentForm



# Create your views here.
class PostList(LoginRequiredMixin,generic.CreateView):
    template_name = 'home.html'
    form=PostForm
    model = PostModel
    fields=['post']
    success_url="/home"

    def form_valid(self, form):
        form.instance.author=self.request.user
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context ['postmodel_list'] = PostModel.objects.order_by('-created_on')
        return context




class PostDetail(generic.DetailView):
    template_name = 'post_detail.html'
    form=CommentForm
    model = PostModel
    fields=['comment']
    success_url="/post_detail"

    def form_valid(self, form):
        form.instance.author=self.request.user
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context ['commentmodel_list'] = CommentModel.objects.order_by('-created_on')
        return context

forms.py

from .models import PostModel,CommentModel
from django import forms

class PostForm(forms.ModelForm):
    class Meta:
        model=PostModel
        fields=['post','author']

class CommentForm(forms.ModelForm):
    class Meta:
        model=CommentModel
        fields=['comment','author']
        label=''

post_detail.html

{% extends 'base.html' %}
{% block content %}
{% load crispy_forms_tags %}
<div class="container">
  <div class="row">
    <div class="col-md-8 mt-3 left mx-auto">
      <div class="card mb-4 block">
        <div class="card-body">
          <h1 class="card-title">{% block title %} {{ postmodel.post }} {% endblock title %}</h1>
          <p class=" text-muted"><a style="text-decoration:none" href="#">@{{ postmodel.author }} </a>| {{ postmodel.created_on }}</p>
          <p class="card-text ">{{ object.content | safe }}</p>
        </div>
      </div>
    </div>
    <div class="col-md-8 mt-3 left mx-auto">
        {% for comments in commentmodel_list %}
        <div class="card mb-4 block">
            <a class="overlay" href="{% url 'comment_detail' postmodel.slug comments.pk %}"style="text-decoration:none"> </a>
            <div class="card-body inner">
              <p style="text-align:right;float:right;margin-top:10px;" class="card-text text-muted h6"><a style="text-decoration:none" href="https://google.com">@{{ comments.author }}</a> </p>
              <h2 class="card-title">{{ comments.comment }}</h2>
            </div>
        </div>
        {% endfor %}
      </div>
  </div>
</div>




<div class="col-md-3 float-right ">
  <button style= "position: fixed; bottom:50px;" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Add New Comment</button>
</div>

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
 <div class="modal-dialog" role="document">
   <div class="modal-content">
     <div class="modal-header">
       <h5 class="modal-title" id="exampleModalLabel">Add Comment</h5>
     </div>
     <div class="modal-body">
       <form method="post" style="margin-top: 1.3em;">
         {% csrf_token %}
         {{ form|crispy }}
         <div class="modal-footer">
           <button type="submit" class="btn btn-primary">Submit</button>
           <button type="submit" class="btn btn-secondary" data-dismiss="modal">Close</button>
         </div>
       </form>
     </div>
   </div>
 </div>
</div>


<style>
  .card{
    box-shadow: 0 16px 48px #E3E7EB;
  }
</style>
{% endblock content %}

2 个答案:

答案 0 :(得分:0)

这里没有链接到所有Post,您只是没有过滤这组注释:

class PostDetail(generic.DetailView):
    # …

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context ['commentmodel_list'] = CommentModel.objects.filter(
            post=self.object
        ).order_by('-created_on')
        return context

您还可以反向访问该关系:

class PostDetail(generic.DetailView):
    # …

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context ['commentmodel_list'] = self.object.post_comment.order_by('-created_on')
        return context

答案 1 :(得分:0)

在您的帖子详细信息中,您是将所有CommentModel对象分配给上下文,而不是按Post进行过滤。

def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context ['commentmodel_list'] = CommentModel.objects.order_by('-created_on')
        return context

尝试

def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context ['commentmodel_list'] = CommentModel.objects.filter(post=self.object).order_by('-created_on')
        return context