Mr Dot
Mr Dot

Reputation: 277

How to bind a comment form to one pot without a choice (Django)

When writing a comment under the article, it becomes possible to choose which post to bring the comment to. How to make comments automatically attach to the post under which it is written.

**views.py**

    
    class AddCommentView(CreateView):
        model  = Comment
        template_name = 'main/post_detail.html'
        form_class = CommentForm
        #fields = '__all__' 
        success_url = reverse_lazy('barbers')
    **models.py**

   

     class Post(models.Model):
          photo       = models.ImageField(upload_to='media/photos/',null=True, blank=True)
          name_barber = models.CharField(max_length=30, null=True, blank=True)
          description = models.TextField()
        
          def __str__(self):
              return self.description[:10]
        
        
        class Comment(models.Model):
          post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE, null=True, blank=True)
          name = models.CharField(max_length=30)
          body = models.TextField(null=True)
          add_date = models.DateTimeField(auto_now_add=True)
        
        
          def __str__(self):
              return '%s - %s' % (self.post, self.name)

**forms.py**

   

 class CommentForm(ModelForm):
        class Meta:
            model = Comment
            fields = ( 'post', 'name', 'body')

Upvotes: 1

Views: 79

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

You can remove the post field from the CommentForm:

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ('name', 'body')

In the path, you specify the primary key of the post to bind the comment to:

path('<int:post_pk>/comment', AddCommentView.as_view(), name='comment')

then in the AddCommentView, you can link the object to the post represented by this primary key in the .form_valid(…) method [Django-doc]:

class AddCommentView(CreateView):
    model  = Comment
    template_name = 'main/post_detail.html'
    form_class = CommentForm
    success_url = reverse_lazy('barbers')

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['post_pk']
        return super().form_valid(form)

Upvotes: 1

Related Questions