~ / blog / development / django-pass-instance-with-predefined-data-to-form-cbv
django 2022-08-23·1 min read

Django: Pass Instance With Predefined Data to Form (CBV)

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.

python
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