26👍
You can use the ordering property:
class Country(models.Model):
name = models.CharField(max_length=80)
class Meta:
ordering = ["name"]
If you set the ordering to the Country class, it shall display them as you want.
12👍
If you can’t or don’t want to use the ordering attribute in class Meta of model, you also can do this:
You need make a Form object, something like:
from django import forms
class PersonForm(forms.ModelForm):
country = forms.ModelChoiceField(queryset=Country.objects.all().order_by('name'))
class Meta:
model = Person
- [Django]-Django Facebook Connect App Recommendation
- [Django]-Slicing a list in Django template
- [Django]-Django – Create user profile on user creation
11👍
There’s 2 good answers here, but I wanted to retain help_text
, blank
, and other settings from the model without having to repeat them and also not change the default ordering on the model. Here’s what I did:
class PersonForm(forms.ModelForm):
class Meta:
model = Person
def __init__(self, *args, **kwargs):
super(PersonForm, self).__init__(*args, **kwargs)
self.fields['country'].queryset = self.fields['country'].queryset.order_by('name')
Essentially I just updated the queryset on the automatically added field to order the way I wanted.
- [Django]-Filter by property
- [Django]-How can my django model DateField add 30 days to the provided value?
- [Django]-Temporarily disable auto_now / auto_now_add
1👍
try adding this into class Meta, inside class Person:
ordering = ['country']
http://docs.djangoproject.com/en/dev/ref/models/options/#ordering
- [Django]-Inject errors into already validated form?
- [Django]-Django request to find previous referrer
- [Django]-Simple Subquery with OuterRef
0👍
In view.py
First: you create the form
form = YourForm(request.POST)
Later your set the query:
form.fields['country '].queryset = YourDBTable.objects.all().order_by('Your_Attr')
- [Django]-'module' object has no attribute 'now' will trying to create a CSV
- [Django]-Django bulk_create with ignore rows that cause IntegrityError?
- [Django]-Django Management Command Argument