sort form field by name

Date: April 10th 2016
Last updated: April 10th 2016

A form model choice field will show records in the order they were added to the database. This example uses a queryset to sort options by name.

useful resources

models.py

class Wave(models.Model):
    #<- snipped ->
    wavename = models.CharField(max_length=40)
    beach = models.ForeignKey(Beach)
    def __str__(self):
        return '{} ({})'.format(self.wavename, self.beach)


class SurfDiary(models.Model):
    #<- snipped ->
    wave  = models.ForeignKey(Wave, blank=True, null=True)
    #<- snipped ->

forms.py

class SurfDiaryForm(forms.ModelForm):

    # Solution: use a queryset and the order_by function 
    # The order_by requires a field name from the model 
    wave = forms.ModelChoiceField(queryset=Wave.objects.all().order_by('wavename'))

    class Meta:
        model = SurfDiary
        fields = [
                # <-snipped->
                'wave', ]

Output
Note that the options are sorted by name, but still show up ast requested by the models str function.

results matching ""

    No results matching ""