jazzblue
jazzblue

Reputation: 2437

Django model select choice, populated with fields from other model instances

Suppose I have a model Car that has a field brand and a model owner that has two field: name and car_brand, whereas the latter should be one of the Car instances brands. I need to have a form where the user is presented with a text field name and a drop down select choice populated with all the brand name of Car instances. How would I achieve that?

Here is the code I am starting with. Feel free to correct. 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, TextInput, Select
from app.models import Owner

class OwnerForm(ModelForm):

    class Meta():
        model = Owner
        fields = ("name", "car_brand")
        widgets = {
            "name" : TextInput(attrs={"class" : "name"}),
            "car_brand" : Select(attrs={"class" : "car_brand"}),
        }

Upvotes: 3

Views: 5589

Answers (1)

David Sanders
David Sanders

Reputation: 4119

You could probably just define a __unicode__ method on your Car model and I think it should work fine. As Daniel mentioned, the form might be getting confused since you've overridden the widgets. I could be wrong, but I thought django automatically rendered attributes on form elements that can be used for styling purposes. Maybe you don't need to override the widgets. If not, you can specify the form field explicitly:

class OwnerForm(ModelForm):
    car_brand = forms.ModelChoiceField(
        queryset=Car.objects.all(),
        widget=Select(attrs={'class': 'car_brand'}),
    )

    class Meta:
        model = Owner
        fields = ('name', 'car_brand')
        widgets = {
            'name': TextInput(attrs={'class': 'name'})
        }

As a side note, is there any reason you don't have a CarBrand model and a foreign key field relating the Car model to it? That would be a more normalized approach to modeling your data.

Upvotes: 2

Related Questions