Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango Admin: Ordering of ForeignKey and ManyToManyField relations referencing User
    primarykey
    data
    text
    <p>I have an application that makes use of Django's <code>UserProfile</code> to extend the built-in Django <code>User</code> model. Looks a bit like:</p> <pre><code>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 </code></pre> <p>I have added a new class to my model:</p> <pre><code>class Team(models.Model): name = models.CharField(max_length=128) manager = models.ForeignKey(User, related_name='manager') members = models.ManyToManyField(User, blank=True) </code></pre> <p>And it is registered into the Admin:</p> <pre><code>class TeamAdmin(admin.ModelAdmin): list_display = ('name', 'manager') admin.site.register(Team, TeamAdmin) </code></pre> <p>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.</p> <p>I have a similar class with:</p> <pre><code>class Meta: ordering = ['name'] </code></pre> <p>That works great! But I don't "own" the <code>User</code> class, and when I try this trick in <code>UserAdmin</code>:</p> <pre><code>class Meta: ordering = ['username'] </code></pre> <p>I get:</p> <p><code>django.core.management.base.CommandError: One or more models did not validate:</code> <code>events.userprofile: "ordering" refers to "username", a field that doesn't exist.</code></p> <p><code>user.username</code> doesn't work either. I could specify, like <code>image_url_s</code> if I wanted to . . . how can I tell the admin to sort my lists of users by <code>username</code>? Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload