I have a model, which has an author ForeignKey, as such:
class Appointment(models.Model):
# ...
author = models.ForeignKey(User)
I want the author field to be set automatically when creating appointment to currently logged-in user. In other words, the author field should not appear in my Form class:
class AppointmentCreateForm(ModelForm):
class Meta:
model = Appointment
exclude = ('author')
There are two problems:
- How to access the form in generic CreateView and set the
author? - How to tell the form to save the excluded field along with the values read from user input?
I’ve modified my generic view subclass as such:
There are few important parts here:
instancefield, which holds the actual model that’s going to be saved.form_classself.object = Noneline, merging the overload and base into one function (I’m not callingsuperinpost).I think it’s a good way to solve pretty common problem, and once again I don’t have to write my own custom view.