I have a form that needs to display the values of a field called model_type in a dropdown list. This list needs to be filtered to just the appropriate year and segment.
This is my form and it works:
class Model_Type__Grouping_Form(ModelForm):
model_type = forms.ModelChoiceField(queryset=Model_Type_Grouping.objects.all())
def __init__(self, *args, **kwargs):
contract_year_segment = kwargs.pop('contract_year_segment', None)
super().__init__(*args, **kwargs)
contract_year = contract_year_segment['contract_year']
segment = contract_year_segment['segment']
contract_year_id = Contract_Year.objects.filter(contract_year = contract_year )[0].id
segment_id = Segment.objects.filter(segment = segment )[0].id
self.fields['model_type'].queryset = Model_Type_Grouping.objects.filter(contract_year_id=contract_year_id, segment_id = segment_id)
class Meta:
model = Model_Type_Grouping
fields = [
"model_type"
]
When user hits save, in the POST request, the selected value of the Model_Type_Grouping is saved under the Contract model. This also works.
model_type_grouping = Model_Type_Grouping.objects.get(pk=request.POST['model_type'])
form_objects = {form_class.__name__.replace('_Form', '').lower(): handle_form(form_class, request.POST, instance=getattr(existing_contract, form_class.__name__.replace('_Form', '').lower(), None)) for form_class in form_classes}
contract_new = Contract(product=product, user=linked_user, model_type_grouping = model_type_grouping, **form_objects)
contract_new.save()
Next, in the GET request, I need to be able to display the saved value. I use the instance keyword. This does not work.
Model_Type_Grouping_Form_data_saved = Model_Type_Grouping.objects.get(pk=contract.model_type_grouping_id)
Model_Type_Form_obj = Model_Type__Grouping_Form(instance=Model_Type_Grouping_Form_data_saved, contract_year_segment=contract_year_segment)
I can’t figure out what I am doing wrong.