Higure
Higure

Reputation: 235

ModelChoiceField: how to show attributes and not objects?

I have two tables (Subject and Languae) with only one attribute, subject and language, each. In the relative form's fields I want to see a dropdown menu with the value of the attribute but with this code:

lang = forms.ModelChoiceField(queryset=Language.objects.order_by('?'), required=False, label='What language want to search?')
subject = forms.ModelChoiceField(queryset=Subject.objects.order_by('?'), required=False, label='Whitch subject you want to search?')

I see the dropdown menu filled of Subject object and Language object which are identical from one onother.

How can i show the actual value of the object?

Upvotes: 0

Views: 1005

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77942

The simplest solution is to implement your Language and Subject models __unicode__ method to make it return the attribute you want to display (or any unicode string built upon any combination of attributes or whatever). In your case:

 class Subject(models.Model):
     subject = models.CharField(....)

     def __unicode__(self):
         return self.subject

and ditto for Language

For more advanced usage, this is documented here: https://docs.djangoproject.com/en/1.6/ref/forms/fields/#modelchoicefield

Note that you don't really have to create a ModelChoiceField subclass to override label_from_instance - you can also just monkeypatch the ModelChoiceField instance with a lambda in your form's __init__

Upvotes: 3

Related Questions