简体   繁体   中英

Django: Allowing user to sort entries in django admin as they want to see on the template

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.

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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM