7

OK, here is the question.

class UserForm(forms.ModelForm):   

    class Meta:
        model = User
        fields = ('team',  'related_projects') 

In models.py the User class is defined as follows:

class User (models.Model):
    team = models.ForeignKey(Team, verbose_name = _('team'))
    related_projects = models.ManyToManyField(Project, blank = True)

Both team and related_projects are rendered as a dropdown-box. The values are all the existing teams in the system, and all the existing projects in the system. That's all right, but they're only ordered by primary key, and I would like to see them ordered alphabetically. Where should I specify ordering for values in a drop-down list?

Hannele
  • 9,301
  • 6
  • 48
  • 68
Graf
  • 1,437
  • 3
  • 17
  • 27
  • 2
    http://stackoverflow.com/questions/923799/reorder-users-in-django-auth – Amarghosh Jun 08 '10 at 12:31
  • Found out that this question has already been discussed on StackOverFlow (http://stackoverflow.com/questions/1474135/django-admin-ordering-of-foreignkey-and-manytomanyfield-relations-referencing-us), and also found the solution here: http://code.djangoproject.com/ticket/6089#comment%3A8 Sorry for taking your time, guys, just after I raised a question correctly, I found out a solution in Google. – Graf Jun 08 '10 at 13:05

1 Answers1

16

You'd need to specify an override for the team field and then you should be able to override the order with its queryset argument. Here I'm assuming the property in Team you want to sort on is name.

class UserForm(forms.ModelForm):
    team = forms.ModelChoiceField(queryset=Team.objects.order_by('name'))

    class Meta:
        model = User
        fields = ('team',  'related_projects') 

You can read more about ModelChoiceField here: http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield

Oli
  • 235,628
  • 64
  • 220
  • 299