ghiotion
ghiotion

Reputation: 285

Django ModelForm - form display values

I have a model:

class SchedulerProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

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

I also have a model that has a M2M relationship with the Scheduler:

class OfficialProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    schedulers = models.ManyToManyField(SchedulerProfile, verbose_name="Your schedulers", related_name="off_schedulers") 

When I create a ModelForm from the OfficialProfile, the form renders the contents of the scheduler multiselect as the username. I'd like to get it to display user.first_name user.last_name in the field instead of the user. I know I can change the unicode return value to accomplish this, but I'd rather not do that for reasons. In the __init__ of the ModelForm, you should be able to do something like:

self.fields['schedulers'].queryset = SchedulerProfile.objects.values('user__first_name', 'user__last_name')

But that doesn't produce the desired results. This seems like a really basic question, but searching for the answer hasn't revealed much.

Upvotes: 0

Views: 571

Answers (1)

Alasdair
Alasdair

Reputation: 308999

Subclass ModelMultipleChoiceField and override label_from_instance.

from django.forms import ModelMultipleChoiceField

class SchedulerProfileChoiceField(ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return "%s %s" % (obj.first_name, obj.last_name)

Then use your multiple choice field in the model form.

class OfficialProfileForm(forms.ModelForm):
    schedulers = SchedulerProfileChoiceField(queryset=SchedulerProfile.objects.all())

Upvotes: 2

Related Questions