如何使用 slug 而不是 pk 在博客文章中显示评论

How to show comment on blogpost with slug instead of pk

提问人:Melanie 提问时间:10/12/2023 更新时间:10/12/2023 访问量:23

问:

我想在文章下方显示评论,但我使用 slug 而不是 pk。我收到以下错误:

IntegrityError 位于 /blogpost-2/comment/ NOT NULL 约束失败:blog_comment.post_id

这是我的代码:

#models.py

`class Comment(models.Model):
    post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    body = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s - %s' % (self.post.title, self.name)`

#views.py

`class AddCommentView(CreateView):
    model = Comment 
    form_class = CommentForm
    template_name = "add_comment.html"
    #fields = '__all__'

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        return super().form_valid(form)
    
    success_url = reverse_lazy('blog')`

#urls.py

`from django.urls import path
from . import views
from .views import BlogView, ArticleView, CategoryView, AddCommentView
urlpatterns = [
    path('<slug:slug>', ArticleView.as_view(), name='blogpost'),
    path('blog/', BlogView.as_view(), name='blog'),
    path('categorie/<str:cats>/', CategoryView, name='category'),
    path('<slug:slug>/comment/', AddCommentView.as_view(), name='add_comment'),
]`

#template add_comment.html

`{% extends 'base.html' %}
{% load static %}
{% block content %}
  <h1>Voeg een reactie toe..</h1>
  <div class="form-group">
    <form method="POST">
      {% csrf_token %}
      {{ form.as_p }}
      <button class="btn btn-primary">Voeg toe</button>
    </form>
  </div>
{% endblock %}`

我尝试了这段代码,但不起作用......

    def form_valid(self, form):
        form.instance.post_slug = self.kwargs['slug']
        return super().form_valid(form)
django django-views 注释 slug

评论


答:

0赞 pleasedontbelong 10/12/2023 #1

您需要先查询帖子:

def form_valid(self, form):
    form.instance.post = Post.objects.get(slug=self.kwargs['slug'])
    return super().form_valid(form)

评论

0赞 Melanie 10/12/2023
是的,它有效!谢谢!