简体   繁体   中英

Django populate choice from ForeignKey

In the following code I am trying to have the Owner form with a drop-down menu that has car brands from the Car model as choices. I do get the drop-down menu but the elements listed as "Car object" each, instead of the brands. How do I get the brands from the Car model into the menu? Thanks.

models.py

from django.db import models

class Car(models.Model):
    brand = models.CharField(max_length=20)

class Owner(models.Model):
    name = models.CharField(max_length=20)
    car_brand = models.ForeignKey(Car)

forms.py

from django.forms import ModelForm, ModelChoiceField
from app.models import Owner

class OwnerForm(ModelForm):
    car_brand = ModelChoiceField(queryset=Car.objects.all())

class Meta():
    model = Owner

Add a __unicode__ function to your model definition.

class Car(models.Model):
    brand = models.CharField(max_length=20)

    def __unicode__(self):
        return u'%s' % (self.brand)

This way you can control what to be displayed

Thanks so much for sharing this, it helped me! In Django 1.8, try: brand = models.ForeignKey(Car)

Dont put car_ in front of the foreign key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM