Django: how to automatically populate request.user in class based generic CreateView
July 09, 2011
Being relatively new to Django, I had struggled to find a neat way to automatically populate a field in a generic CreateView form. I stumbled across the following on Stack Overflow. Big thankyou to Yuji Tomita for the answer.
In summary, the CreateView subclass I ended up with looked along the lines of:
class SpecialCreateView(CreateView): form_class = SpecialForm def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.save() return HttpResponseRedirect('/')
And to exclude the field from the form, in forms.py:
class SpecialForm(ModelForm): class Meta: model = Special exclude = ('user',)
Once that was set up as above, the rest worked like clockwork. Class based generic views are so incredibly flexible, I never cease to be surprised!