Pass Instance With Predefined Data to Form (CBV)

Pass Instance With Predefined Data to Form (CBV)

August 21, 2022
forms

In case when you need to initialize form with already predefined details of the form instance, for example form that add comment to a post - you can predefine post_id in the form instance instead applying it in the save() method.

class AddCommentView(CreateView):
    template_name = 'comment.html'
    model = Comment
    form_class = CommentForm
    
    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()

        post = Post.objects.get(pk=self.kwargs['post_id'])
        instance = self.model(post=post)
        kwargs.update({'instance': instance})

        return kwargs

Comments