My apologies, I really didn’t intend to be cryptic. Please allow me to try and explain.
The CreateView.form_valid
method comes from the ModelFormMixin
class, which looks like this:
def form_valid(self, form):
"""If the form is valid, save the associated model."""
self.object = form.save()
return super().form_valid(form)
The call to super().form_valid(form)
calls FormMixin.form_valid
, which looks like this:
def form_valid(self, form):
"""If the form is valid, redirect to the supplied URL."""
return HttpResponseRedirect(self.get_success_url())
If we combine the functionality of these two methods into one sequence of code, you get:
def form_valid(self, form):
self.object = form.save()
return HttpResponseRedirect(self.get_success_url())
This is what effectively gets executed when you call super().form_valid(form)
in your form_valid
method. This means that you could copy these lines into your form_valid, such that it looks like this:
def form_valid(self, form):
print('test: '+ str(form.cleaned_data['addSomething']))
self.object = form.save()
return HttpResponseRedirect(self.get_success_url())
Why might you want to do this?
Because you need to do something between the self.object = form.save()
and the return
statement, and that “something” is to create the associations between the Person
and Label
instances.
Having said that, if your coding standards require you to call super
so as to avoid theoretical problems potentially happening in the future if these CBVs were to fundamentally change, you do have an alternative.
Again, if you look at what’s happening with super().form_valid(form)
, you’re calling a function, and it’s returning a variable to you. You want to return that variable from your function, but that doesn’t mean you need to do it immediately or at the point where it’s being called.
It’s perfectly valid to write a form_valid
method that looks like this:
def form_valid(self, form):
print('test: '+ str(form.cleaned_data['addSomething']))
response = super().form_valid(form)
# Do stuff, like create links between `People` and `Label`
return response