Reputation: 331
I have a many-to-many field named countries.
These countries are rendered as a list one after the other like a stack on my template.
America
Australia
India
China
Now I want the admin-user to be able to configure the order of how they are listed on the template. No specific sort method (alphabetic and created on ).
So I wanted suggestions on how this can be done.
Upvotes: 1
Views: 388
Reputation: 11228
In your Country model add a sorting field. By adding Meta ordering you give a default ordering:
class Country(models.Model):
name = models.CharField("Name", max_length=200)
sorting = models.IntegerField("Ordering", blank=True, null=True,
help_text="A number. Use tens or hundreds to be able to add Counties.")
class Meta:
ordering = ('sorting', 'name')
The ordering in your model is the default. The sorting can also be set in your query or ModelAdmin. In views.py:
countries = Country.objects.all().order_by('sorting', 'name')
In admin.py:
class CountryAdmin(admin.ModelAdmin):
ordering = ['sorting', 'name' ]
#Bonus tip: editing in the list view!
list_editable = ['sorting', ]
#Need sorting in list_display to get list_editable to work.
list_display = ['title', 'sorting']
I used ['sorting', 'name' ] because your countries get sorted by 'sorting' but if sorting is not filled (or equal) then sorting will fallback to alphabetic 'name'.
Remember: If you use blank=True and null=True on your model field. Then the sorting field will be optional. But no value is Null and that is before any number [Null, Null, 1, 2, 3]. This could be undesired. To make sorting required leave "blank=True, null=True" out.
Is't smart to use tens or hundreds so the list can be adjusted and countries can be fitted in.
If you try to fix wierd country names Like "The Netherlands", than is suggest you make a sorting = models.CharField() and put prepopulated_fields in your admin:
prepopulated_fields = { 'sorting': ('name', ) }
Your editor only has to delete "The " to get The Netherlands next to Nepal instead of Thailand.
With the data sorted your template is simple:
{% for country in countries %}{{ country.name }}{% endfor %}
Upvotes: 1