[Django]-In a form, How to display fields from other models using foreign keys, specially a field with choices?

5👍

You probably want to add custom field to your ModelForm and exclude original foreign key:

class EmailForm(forms.ModelForm):
    country_name = forms.CharField()

    class Meta:
        model = YourModel
        exclude = ('country',)

Then, in your view you should manualy create (or get if it exists) your company and save the form:

def foo(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            form.instance.country = Country.objects.get_or_create(cname=form.cleaned_data['country_name'])
            form.save()

0👍

I think the answer maybe in this post Django – Display a ModelForm foreign key field

However, I haven’t been able to successfully make it work yet.

👤Linh

Leave a comment