Saving forms.Form that references multiple Models and compensate for "cleanned_data" which don't work for blank charfields

Hello,

I would like to create a Form that includes some fields from multiple Models. So, I created a form.Form by describing each field independently, and then I validate and save my fields in each of the used Models by using the cleaned_data method.

Several questions arise:

  • Is there a more efficient way to generate a Form that references multiple Models?
  • Is it necessary to use the cleaned_data method to retrieve field values, as it doesn’t work with empty CharFields?

Thank you.

My form

class MyForm(forms.Form):
    model1_attributeA= forms.ChoiceField(
        choices=Model1._meta.get_field("attributeA").choices,
        required=True,
        widget=forms.Select(attrs= {'class': 'form-select'}),
    )
    model2_attributeB= forms.CharField(
        required=True,
        widget=forms.NumberInput(attrs={'class': 'form-control'}),
    )

My view

my_form = MyForm(request.POST)
if my_form.is_valid():
    objectA = Model1.objects.get(pk = 45)
    if my_form.cleaned_data['attributeA']:
        object1.attributeA = my_form.cleaned_data['attributeA']
        object1.save()

    object2 = Model2.objects.get(pk = 23)
    if my_form.cleaned_data['attributeB']: #None if blank field..
        object2.attributeB = my_form.cleaned_data['attributeB']
        object2.save()