Imagine we're developing a message system, and each Message has a foreign key for sender.
We're using ModelForms, and there is a MessageForm that infers its fields from Message.
Of course, we don't want the user to be able to spoof sender by posting a different sender ID.
Therefore, we must exclude sender from ModelForm and fill it from session on post.
Where and how should I assign arbitrary data to ModelForm fields?
In my example, I probably want to access session so we need to access to request as well.
Does this mean the code has to be in the view, right after the form has been created?
How do we assign a form field from code and make sure it overrides POST data?
(Of course, the example is pretty fictional and is here just to illustrate the problem.)
You can just exclude it as you have and then when processing the form in the view do:
Alternatively, you can do it in the save method of the form; for this you need to save the request object momentarily in the form. Something like the following:
I prefer the second way myself as it helps encapsulate the logic regarding that model and it's data in one neat place.