A Better Way – Don’t!

In an earlier post, I talked about using form.save(commit=False) in a class based view, and I showed a way to do it.  However, I wasn’t looking far enough back to see the real question:

How can I add information not found on the form to the object before saving?

Thanks to a reply way down in this Google Groups post, I found what I needed, and I kicked my self for not seeing this earlier. Since I was using the default form logic to save the object, I could send the additional value to the form.

    ## Include the instance object before saving
    def form_valid(self, form):
        form.instance.institution = self.institution
        return super(EventCreateView,self).form_valid(form)

I like this solution better than what I provided in the earlier post because it is a better object oriented approach.

Of course, I have used the older example all over my applications, so I’ve got some refactoring to do.

Comments are closed.