Django - form.instance property

Hello. Here is a view from my project:

class PostCreateView(CreateView):
    form_class = PostForm
    template_name = 'post_create.html'
    success_url = reverse_lazy('post_list')

    def form_valid(self, form):
        print(form.cleaned_data)
        form.instance.user = self.request.user 
        return super().form_valid(form)

Form:
class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' `

The line form.instance.user = self.request.user sets the user property on my Post model. How does this actually work? What does form.instance actually reference in order for this to happen? Thanks.

I haven’t traced all the code through exactly, but I believe that CreateView will create the model instance (in your case, a Post record) and attach it to the view as object. Then, when creating the form instance, the object (i.e., the Post record) is connected to the form via get_form_kwargs.

See https://github.com/django/django/blob/master/django/views/generic/edit.py#L107 for the spot where that happens.

Great that helps a lot. Thanks.