Ross
Ross

Reputation: 2417

django filter choices, order choices on template in order written in filter

I have a Django Filter that that has 4 choices. I would like to order these choices on the template in the order that I have written them in the filter.

filter.py:

RarityChoices = {
  ('common', 'Common'),
  ('uncommon', 'Uncommon'),
  ('rare', 'Rare'),
  ('mythic', 'Mythic')
}

rarity  = ChoiceFilter(field_name='rarity', empty_label='Any', choices=sorted(RarityChoices), widget=RadioSelect())

template.html:

<div>
  <label class="mb-1" for="id_type">Rarity:</label>
  {{ card_filter.form.rarity}}
</div>

Screenshot:

enter image description here

If I change my filter to:

rarity  = ChoiceFilter(field_name='rarity', empty_label='Any', choices=RarityChoices, widget=RadioSelect())

The filter looks like this on the template:

enter image description here

Neither are in the order that I want or in the order listed in the filter.py file.

Upvotes: 0

Views: 262

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 114098

RarityChoices = {
  ('common', 'Common'),
  ('uncommon', 'Uncommon'),
  ('rare', 'Rare'),
  ('mythic', 'Mythic')
}

is a set ... sets are unordered ... change it to a list or a tuple

RarityChoices = [  # [ is for list
  ('common', 'Common'),
  ('uncommon', 'Uncommon'),
  ('rare', 'Rare'),
  ('mythic', 'Mythic')
]

Upvotes: 5

Related Questions