Users Full Name in model form?

196 views
Skip to first unread message

Streamweaver

unread,
Sep 4, 2009, 2:26:16 PM9/4/09
to Django users
I had a model that lists an owner with a FK relationship to the Users
table.

When using model form the dropdown for the owner field defaults to the
username.

I'd like to override that to use a users name as the choice portion of
the dropdown sorted by users last name but I'm having trouble thinking
through how to do this.

Can anyone point me to an example of something like this?

Streamweaver

unread,
Sep 4, 2009, 5:41:29 PM9/4/09
to Django users
I put a solituion for this in the form of where this is passed a user
object.

class UserChoiceField(forms.ModelChoiceField):
'''
Returns a select field with user names formatted by last and first
name
where available and ordered by last name.
'''
def label_from_instance(self, obj):
if obj.last_name or obj.first_name:
display = ", ".join((obj.last_name, obj.first_name))
else:
display = obj.username
return display

Anthony Simonelli

unread,
Sep 4, 2009, 4:50:06 PM9/4/09
to django...@googlegroups.com
Is this within the Admin interface? If so, I'm having a similar
problem. I have a model called Request with a FK relationship to an
Employee model. Within the Admin interface, when adding a Request,
the drop-down of the Employees selection read "Employee Object". This
is also the case when listing the Employees. There is no way to
distinguish between the employees.

How do I change, what I think is called the "string representation" of
the object within the Admin interface. Also, is there some sort of
naming convention when creating models to get these fields
automatically?

Streamweaver

unread,
Sep 7, 2009, 9:00:20 PM9/7/09
to Django users
This was through a custom form in a public view. I haven't done much
with admin forms but maybe someone else knows?



On Sep 4, 4:50 pm, Anthony Simonelli <asimonell...@gmail.com> wrote:
> Is this within the Admin interface?  If so, I'm having a similar
> problem.  I have a model called Request with a FK relationship to an
> Employee model.  Within the Admin interface, when adding a Request,
> the drop-down of the Employees selection read "Employee Object".  This
> is also the case when listing the Employees.  There is no way to
> distinguish between the employees.
>
> How do I change, what I think is called the "string representation" of
> the object within the Admin interface.  Also, is there some sort of
> naming convention when creating models to get these fields
> automatically?
>

Mike Dewhirst

unread,
Sep 7, 2009, 10:49:30 PM9/7/09
to django...@googlegroups.com
Visit ...

http://docs.djangoproject.com/en/dev/intro/tutorial01

... and search in that page for "Wait a minute"

It indicates that you can return whatever string (actually unicode)
representation you want as constructed from the object attributes when
you bring an object via foreign key.

Mike



> >
>
>

Reply all
Reply to author
Forward
0 new messages