[Answered ]-Add comments to article django createview foreignkey

2👍

I think this is you want

class CreateArticleComment(CreateView):
    model = ArticleComment 
    fields = ('text',)

    def post_valid(self, form):
        article = get_object_or_404(Article, 
                                    slug=article.slug) # Replaced 'Post' with 'Article'
        articlecomment = form.save(commit=False)
        articlecomment.author = self.request.user
        articlecomment.article = article
        articlecomment.save()
        return redirect('articles:article-detail', slug=article.slug)

    def get_success_url(self):
        return reverse_lazy('articles:article-list')

0👍

You are assigning a queryset to a foreign key field:

class CreateArticleComment(CreateView):
    model = ArticleComment 
    fields = ('text',)

def post_valid(self, form):
    post = get_object_or_404(Post, 
                                slug=article.slug)
    article = Article.objects.all()                <----------------------------
    articlecomment = form.save(commit=False)
    articlecomment.author = self.request.user
    articlecomment.article = article
    articlecomment.save()
    return redirect('articles:article-detail', slug=article.slug)

def get_success_url(self):
    return reverse_lazy('articles:article-list')

the line

article = Article.objects.all()

needs to be changed to

article = get_object_or_404(Article, slug=self.kwargs['slug'])

As we want to assign comment to a specific article, whose slug is present in current url as :

http://example.com/article-slug/comment/

which will allow us to get the related article on which the user is commenting.

Leave a comment