Replace textfields with dropdown select fields
- by 47
I have three model classes that look as below:
class Model(models.Model):
model = models.CharField(max_length=20, blank=False)
manufacturer = models.ForeignKey(Manufacturer)
date_added = models.DateField(default=datetime.today)
def __unicode__(self):
name = ''+str(self.manufacturer)+" "+str(self.model)
return name
class Series(models.Model):
series = models.CharField(max_length=20, blank=True, null=True)
model = models.ForeignKey(Model)
date_added = models.DateField(default=datetime.today)
def __unicode__(self):
name = str(self.model)+" "+str(self.series)
return name
class Manufacturer(models.Model):
MANUFACTURER_POPULARITY_CHOICES = (
('1', 'Primary'),
('2', 'Secondary'),
('3', 'Tertiary'),
)
manufacturer = models.CharField(max_length=15, blank=False)
date_added = models.DateField(default=datetime.today)
manufacturer_popularity = models.CharField(max_length=1,
choices=MANUFACTURER_POPULARITY_CHOICES)
def __unicode__(self):
return self.manufacturer
I want to have the fields for model series and manufacturer represented as dropdowns instead of text fields. I have customized the model forms as below:
class SeriesForm(ModelForm):
series = forms.ModelChoiceField(queryset=Series.objects.all())
class Meta:
model = Series
exclude = ('model', 'date_added',)
class ModelForm(ModelForm):
model = forms.ModelChoiceField(queryset=Model.objects.all())
class Meta:
model = Model
exclude = ('manufacturer', 'date_added',)
class ManufacturerForm(ModelForm):
manufacturer = forms.ModelChoiceField(queryset=Manufacturer.objects.all())
class Meta:
model = Manufacturer
exclude = ('date_added',)
However, the dropdowns are populated with the unicode in the respective class...how can I further customize this to get the end result I want?
Also, how can I populate the forms with the correct data for editing? Currently only SeriesForm is populated. The starting point of all this is from another class whose declaration is as below:
class CommonVehicle(models.Model):
year = models.ForeignKey(Year)
series = models.ForeignKey(Series)
....
def __unicode__(self):
name = ''+str(self.year)+" "+str(self.series)
return name