Setting the Instance on a Django Model Form Class Based View
I've been converting some of my code to the new Django 1.3 class-based views recently, and I must say that overall, it's been quite a frustration. I see the merits of class based views. It has resulted in some shorter code in certain places, and helped avoid some duplication (that I previously avoided equally well with functional views).
Anyway, that aside, there's one thing I found impossible to find any reference to online, and that is how to set an instance on a model form through class-based views. The best solution (that I can see) seems to be to override the get_form_kwargs function in your View class, like this:
def get_form_kwargs(self):
kwargs = super(YourView, self).get_form_kwargs()
kwargs['instance'] = self.request.user
return kwargs
This will give the kwargs to the model form an 'instance' key, that contains the model that should prefill all the fields. It's a clean and short solution, but it might have helped had the documentation told me from the onset that there is no straight-forward variable or function for this goal. Or is there? If there is, please let us know in the comments.
If you found this post interesting, you might also like our blog post, How to create separate Name and Surname inputs as one widget in Django
