user2161049
user2161049

Reputation: 893

Django ModelChoiceField show specific field and not the pk field

I'm using django 1.4.5 and I need to show a field in user profile which called 'uuid'

and it is not the pk.

I heard about to_field_name of ModelChoiceField but apparently this does not work due to internal bug in django's core.

does anyone manage to show field that is not the pk field?

I was trying to use this patch: https://gist.github.com/drdaeman/5326761

but no avail.

10x

Upvotes: 0

Views: 779

Answers (1)

Adrián
Adrián

Reputation: 6255

Right from the docs:

The unicode method of the model will be called to generate string representations of the objects for use in the field’s choices; to provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model object, and should return a string suitable for representing it. For example:

So two options:

# in your model
def __unicode__(self):
    return unicode(self.uuid)

or, much better if you need to keep a different string representation:

from django import forms

class UUIDChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return unicode(obj.uuid)

class FormWithUUIDChoiceField(forms.form):
    field1 = UUIDChoiceField(queryset=..., ...)

Upvotes: 1

Related Questions