django 如何用slug代替pk显示blogpost上的评论

p8h8hvxi  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(105)

我想在一篇文章下面显示评论,但我用了slug而不是pk。我得到以下错误:
/blogpost-2/comment/ NOT NULL constraint failed: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')`

url.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)
uidvcgyl

uidvcgyl1#

您需要先查询文章:

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

相关问题