views:

865

answers:

3

Hello,

I have an application that makes use of Django's UserProfile to extend the built-in Django User model. Looks a bit like:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    # Local Stuff
    image_url_s = models.CharField(max_length=128, blank=True)
    image_url_m = models.CharField(max_length=128, blank=True)

    # Admin
    class Admin: pass

I have added a new class to my model:

class Team(models.Model):
    name = models.CharField(max_length=128)
    manager = models.ForeignKey(User, related_name='manager')
    members = models.ManyToManyField(User, blank=True)

And it is registered into the Admin:

class TeamAdmin(admin.ModelAdmin):
    list_display = ('name', 'manager')

admin.site.register(Team, TeamAdmin)

Alas, in the admin inteface, when I go to select a manager from the drop-down box, or set team members via the multi-select field, they are ordered by the User numeric ID. For the life of me, I can not figure out how to get these sorted.

I have a similar class with:

class Meta:
    ordering = ['name']

That works great! But I don't "own" the User class, and when I try this trick in UserAdmin:

class Meta:
    ordering = ['username']

I get:

django.core.management.base.CommandError: One or more models did not validate: events.userprofile: "ordering" refers to "username", a field that doesn't exist.

user.username doesn't work either. I could specify, like image_url_s if I wanted to . . . how can I tell the admin to sort my lists of users by username? Thanks!

+2  A: 

One way would be to define a custom form to use for your Team model in the admin, and override the manager field to use a queryset with the correct ordering:

class TeamForm(forms.ModelForm):
    manager = forms.ModelChoiceField(queryset=User.objects.order_by('username'))

    class Meta:
        model = Team

class TeamAdmin(admin.ModelAdmin):
    list_display = ('name', 'manager')
    form = TeamForm
Daniel Roseman
Thanks, Daniel!
dannyman
+1  A: 

This

class Meta:
    ordering = ['username']

should be

    ordering = ['user__username']

if it's in your UserProfile admin class. That'll stop the exception, but I don't think it helps you.

Ordering the User model as you describe is quite tricky, but see http://code.djangoproject.com/ticket/6089#comment%3A8 for a solution.

Greg
A: 

give the models a unicode method

kanja