Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am making a test form using ModelForm which has two models.

  1. Country
  2. Email

I am creating a form based on Email models. The Country model has name field, with the values given by the COUNTRIES list. I want to display name field in the EmailForm, with all the COUNTRIES values. Do I have to use a foreign key? Please guide.

My models look like this:

COUNTRIES = (('IND', 'India'), ('PAK', 'Pakistan'), ('AMR', 'America'))

class Country(models.Model):
    name = models.CharField(max_length=3, choices=COUNTRIES)

class Email(models.Model):
    title = models.CharField(max_length=50)
    country = models.ForeignKey('Country')
    sender = models.EmailField(max_length=20)
    date = models.DateTimeField()
    text = models.CharField(max_length=20)

class EmailForm(ModelForm):
    class Meta:
        model = Email

If I generate a form out of this. it shows a drop down menu which is blank. How to get values from the list?

like image 746
escapee Avatar asked Dec 06 '25 10:12

escapee


1 Answers

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()
like image 198
Daniil Ryzhkov Avatar answered Dec 08 '25 01:12

Daniil Ryzhkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!