Show the values in dropdown in reverse order in Django Forms
class FineForm(forms.ModelForm):
class Meta:
model = Fine
fields = ['student', 'fine']
widgets = {
'student': forms.Select(attrs={'class': 'form-control'}),
'fine': forms.TextInput(attrs={'class': 'form-control'}),
}
I have this Django form. The student field is a foreign key. I want to show the students in reverse order in this form in the template. Help please.
you can always do anything with choices in form.
Easy, but not the best way:
class FineForm(forms.ModelForm):
... # your staff
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# after super() widget.choices in Select is a list
self.fields['students'].widget.choices = self.fields['students'].widget.choices[::-1]
I don't like this solution.
You need revert choices only before render, isn't it? That's why you should try other possibilities:
- add order_by in Student._meta
- override order_by in self.fields['students'].queryset
- use own ModelChoiceGenerator for Student.objects
- use FormFieldCallback in FormFactory
- define your own Field.widget.render or form.render
- render field manually in your template
- e.t.c (i don't know your project)