I have two forms: one that takes user information (name, birthdate, etc): formA. And another one that contains a textfield the user can input text into: formB.
formB’s model has the actual textfield, and a “name” that links it to the user this text belongs to. This field is called text_name. text_name is a foreign key linked to the Name model (that’s linked to formA).
In my view’s template, I am only allowing the user to see the textbox they can input information into from formB, and they can also see all the fields in formA.
This means the text_name dropdown box is not displayed.
formA is currently being prepopulated with data from a different session.
This is my view:
def name(request):
ses = request.session.get('ses', None)
formA = Name_Form(request.POST, instance = ses)
formB = Text_Form(request.POST or None)
formB.text_name = ses
if request.method == 'POST':
formB.text_name = ses
if formA.is_valid() and formB.is_valid():
formB.note_job = ses
a = formA.save()
a.save()
b = formB.save()
b.save()
formB is not valid because text_name is not being populated. I tried populating using this line:
formB.text_name = ses
but that did not work.
How do I automatically populate text_name with the information inputted already without actually displaying text_name in my template and therefore forcing the user to actually choose the appropriate text_name manually.
If you want to do extra processing on a model instance of a modelform before saving, there are at least two simple options:
Access the modelform model instance before saving through form.instance:
formB.instance.text_name = ses; formB.save()Save manually with commit=False:
objB = formB.save(commit=False); objB.text_name = ses; objB.save(), in that case make sure that Text_Form has ‘text_name’ in it’s excluded field list.