get field from anther model in model form code example

Example 1: get field from anther model in model form

<form action="." method="POST">
    {% csrf_token %}
    {{ company_form.as_p }}
    {{ account_form.as_p }}
    <button type="submit">
</form>

Example 2: get field from anther model in model form

if request.method == 'POST':

    company_form = CompanyForm(request.POST)
    account_form = AccountForm(request.POST)

    if company_form.is_valid() and account_form.is_valid():

        company_form.save()
        account_form.save()
        return HttpResponseRedirect('/success')        

    else:
        context = {
            'company_form': company_form,
            'account_form': account_form,
        }

else:
    context = {
        'company_form': CompanyForm(),
        'account_form': AccountForm(),
    }

return TemplateResponse(request, 'your_template.html', context)

Example 3: get field from anther model in model form

class CompanyForm(forms.ModelForm):
    class Meta:
        fields = [...]
        model = Company

class AccountForm(forms.ModelForm):
    class Meta:
        fields = [...]
        model = Account