How do I get a form to perform cleaning with the instance set before it renders on a browser?
I do:
form.instance = MyModel.Objects.get(pk=a_number)
but I find that during cleaning (i.e in clean())
:
print(self.instance)
tells me the instance is fresh (not the one I assigned). How do I preserve the instance through rendition and unto cleaning (i.e.making sure the form renders using the instance I specify … and passes the same up to cleaning)?
There is nothing to clean on a form with no data submitted. There’s no post data being submitted to clean.
See the docs at The Forms API | Django documentation | Django to understand the difference between a bound and unbound form.
clean()
is running after submission.
Here is the scenario
1. Before rendering, In the CBV (FormView):
form.instance = MyModel.Objects.get(pk=a_number)
# Also set some intial values in the form
2. Render (we are in the browser)
The form displays initial values – I make some inputs in the associated formset
(not the form … but the parent formset
. Trusting that data in the form is okay)
3. Submission. clean() runs
def clean(self):
super().clean()
print(self.instance)
→ at his point, I get a fresh instance that is different from what I assigned in the view.
print(self.cleaned_data)
shows the data from the form … but without the Object
Is this normal?
Yes, absolutely. Not only normal, but expected and how the HTTP protocol works.
Each request creates a new instance of the CBV. (Each request also constitutes a new function call for an FBV.)
There is no “state” maintained between requests.
What you do in a view between the time the view is called with the request and the time the response is returned, is separate and independent of any other invocations of that view.