显示特定博客帖子特有的评论

时间:2020-01-14 19:20:14

标签: python html django

我想在每个博客文章中显示该博客文章唯一的评论,但是当我单击评论发布表格上的提交时,会抛出错误

/ post / 6 / comment /中的IntegrityError NOT NULL约束失败:blog_postcomment.Post_id

我在数据库中手动添加了注释,但是注释未显示在页面上。

HTML

{% block content %}
    <div class="container">
      <div class="row">
        <div class="col-md-8 card mb-4  mt-3 left  top">
          <div class="card-body">
            {% if comment_list %}
            <h2 class="post-title">Comments</h2>
            {% for comment in blog_postcomment.post %}
            <p class=" text-muted">{{ comment.author }} | {{ comment.post_date }}</p>
            <p class="card-text ">{{ comment.description | safe }}</p>
            {% endfor %}
            {% endif %}
          </div>
        </div>
      </div>
    </div>
{% block content %}

模型

class PostAuthor(models.Model):
    user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
    bio = models.TextField(max_length=400, help_text="Enter your bio details here.")

    class Meta:
        ordering = ["user", "bio"]

    def get_absolute_url(self):
        return reverse('post-by-author', args=[str(self.id)])

    def __str__(self):
        return self.user.username


class Post(models.Model):
    title = models.CharField(max_length=200, unique=False)
    slug = models.SlugField(max_length=200, null=True, blank=True)
    author = models.ForeignKey(PostAuthor, on_delete=models.CASCADE, null=True, blank=True)
    updated_on = models.DateTimeField(auto_now=True)
    content = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=STATUS, default=0)

    class Meta:
        ordering = ['-created_on']

    def get_absolute_url(self):
        return reverse('post-detail', args=[str(self.id)])

    def __str__(self):
        return self.title


class PostComment(models.Model):
    description = models.TextField(max_length=1000, help_text="Enter your comment here.")
    author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    post_date = models.DateTimeField(auto_now_add=True)
    Post = models.ForeignKey(Post, on_delete=models.CASCADE)

    class Meta:
        ordering = ["post_date"]

    def __str__(self):
        len_title = 75
        if len(self.description) > len_title:
            titlestring = self.description[:len_title] + '...'
        else:
            titlestring = self.description
        return titlestring

查看

class PostListbyAuthorView(generic.ListView):
    model = Post
    template_name = 'blog/post_list_by_author.html'

    def get_queryset(self):
        id = self.kwargs['pk']
        target_author = get_object_or_404(PostAuthor, pk=id)
        return Post.objects.filter(author=target_author)

    def get_context_data(self, **kwargs):
        context = super(PostListbyAuthorView, self).get_context_data(**kwargs)
        context['post'] = get_object_or_404(PostAuthor, pk=self.kwargs['pk'])
        return context


class IndexPage(generic.ListView):
    queryset = Post.objects.filter(status=1).order_by('-created_on')
    template_name = 'blog/index.html'


class PostList(generic.ListView):
    queryset = Post.objects.filter(status=1).order_by('-created_on')
    template_name = 'blog/all_posts.html'


class PostDetail(generic.DetailView):
    model = Post
    template_name = 'blog/post_detail.html'


class PostCreate(CreateView):
    model = Post
    fields = '__all__'
    template_name = 'blog/post_form.html'


class PostUpdate(UpdateView):
    model = Post
    fields = ['content', 'title']
    template_name = 'blog/edit_post.html'


class PostComment(LoginRequiredMixin, CreateView):
    model = PostComment
    fields = ['description', ]
    template_name = 'blog/comment_form.html'

    def get_context_data(self, **kwargs):
        context = super(PostComment, self).get_context_data(**kwargs)
        context['post'] = get_object_or_404(Post, pk=self.kwargs['pk'])
        return context

    def form_valid(self, form):
        form.instance.author = self.request.user
        form.instance.post = get_object_or_404(Post, pk=self.kwargs['pk'])
        return super(PostComment, self).form_valid(form)

    def get_success_url(self):
        return reverse('post-detail', kwargs={'pk': self.kwargs['pk'], })

urlpatterns = [
    path('', views.IndexPage.as_view(), name='index'),
    path('posts/', views.PostList.as_view(), name='all-posts'),
    path('post/detail/<int:pk>', views.PostListbyAuthorView.as_view(), name='post-by-author'),
    path('post/author/<int:pk>', views.PostDetail.as_view(), name='post-detail'),
    path('post/create/', views.PostCreate.as_view(), name='post-create'),
    path('post/<int:pk>/edit/', views.PostUpdate.as_view(), name='post-edit'),
    path('post/<int:pk>/comment/', views.PostComment.as_view(), name='post-comment'),
    path('accounts/', include('django.contrib.auth.urls')),
]

1 个答案:

答案 0 :(得分:1)

第一个问题: LIKE中首字母的大小写不同 此处:model .query(function(qb) { const keyword = "pattern"; qb.whereRaw(`(information->'description')::TEXT LIKE '%${keyword}%'`) }) .fetch(); 此处:post