10

how can I change the order of the values in the ModelChoiceField billing_company?

models.py

class Company(models.Model):
    name = models.CharField(max_length=30, unique=True)

forms.py

billing_company = forms.ModelChoiceField(Company.objects, required=True)

Thanks for your help. Tom

2 Answers 2

11

ModelChoiceField takes a QuerySet as its first parameter, so you should be able to pass an ordered set:

forms.ModelChoiceField(Company.objects.order_by('-pk'), required=True)
0
0

If you want to sort it in the template, you can manually render the form and iterate over the options and sort them using the dictsort templatetag (or any other templatetag that sorts according to what you like), e.g.

{% for value, option in form.fields.billing_company.choices|dictsort:1 %}
    <option value="{{ value }}">{{ option }}</option>
{% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.