Login

Tag "sort"

Snippet List

Sophisticated order_by sorting

I wanted to sort a CharField which consists of digits in a different way. This field is a matricle number field (some kind of registration number for students. They have matricle numbers in the format YYxxxxxx - which means "YY" are the last two digits of the year they started studying.) So I wanted to sort them in a way that they appear like this: 5000000, 5000001, ... , 9999998, 9999999, 0000000, 0000001, ... , 1200000, ... , 4999999 Took me some time to find out how to do this efficiently in PostgreSQL, and so I thought I'd share it here. The important stuff is in the model "Candidate" to use a special "objects" object manager which uses a special QuerySet as well. Here lies the "magic": If there is a ordering required that contains "mnr", then a special on-the-fly calculated field will be added to the queryset called "mnr_specialsorted". Now it is possible to do things like `Candidate.objects.filter( firstname__contains="Pony" ).exclude( lastname__contains="Java" ).order_by("lastname", "-mnr")` For other database engines you might want to change the MNR_SORTER variable to fit your needs.

  • sort
  • orderby
  • sorting
  • ordering
Read More

Admin Model Sorting

This allows you to order the models on the index page of the administration site in a custom way. This modification goes in the index method of django.contrib.admin.sites.AdminSite. I personally monkey patched it in where my models are loaded and registered with the admin site. Be careful that if you add new models you update the sorting dictionary, else you will get a key error. If no sorting is defined for an app, it will default to alphabetical order. Note that you'll probably want to also insert this into the app_index function as well. --- If you like my work, please check out my employer's site at 829llc.com - Dan

  • models
  • admin
  • sort
  • sorting
  • app-models
Read More

Drag and drop ordering of admin list elements for Grappelli

Adds drag-and-drop ordering of rows in the admin list view for [Grappelli](http://code.google.com/p/django-grappelli/). This is based on [Snippet #2057](http://djangosnippets.org/snippets/2057/) and fixes some bugs as well as switching to jQuery/jQuery UI provided by Grappelli. No additional files need to be installed. The model needs to have a field holding the position and that field has to be made list_editable in the ModelAdmin. The changes of the ordering are applied after clicking 'Save'.

  • admin
  • sort
  • jquery
  • order
  • sortable
  • grappelli
Read More

Drag and drop ordering of admin list elements using jQuery UI

Adds drag-and-drop ordering of rows in the admin list view. The only requirements is that the model has a field holding the position and that the field is made list_editable in the ModelAdmin. The changes of the ordering are applied after clicking 'Save'. The included javascript uses [jQuery UI's sortable](http://jqueryui.com/demos/sortable/) plugin Inspired by snippets [#1053](http://djangosnippets.org/snippets/1053) and [#998](http://djangosnippets.org/snippets/998/). Another similar snippet using AJAX is [#2047](http://djangosnippets.org/snippets/2047/).

  • admin
  • sort
  • jquery
  • order
  • sortable
Read More

SortableModel - abstract model class for sortable records

If you have a model that has an "ordering" column, and you want to be able to re-position records (eg, order items by priority), this base class should make it fairly easy. To use it, you extend your model using this abstract class, then hook up the pre_save event to the pre_save event of the base class, and you're good to go. Whenever you save an item, it ensures that it has a valid "order" number. The meat of this class is the "move()" method. Just call instance.move(number) where instance is your model instance, and this class will do all the logic necessary to shift around the order numbers for you.

  • sort
  • order
  • sortable
  • orderable
  • sorted
  • ordered
Read More

Dynamic tabular inlines with optional drag-n-drop sorting

This jQuery javascript enables dynamic add/delete of rows in tabular inlines. It adds a "+" icon at the bottom of the inline to allow addition of new rows, and replaces the default delete checkbox with a "x" icon for deletion, giving you the possibility to add/delete rows instantly without reloading the page. In addition, it gives you drag-n-drop ordering functionality with a named position model field using jQuery UI Sortable. **Usage (see below for example):** Just include the javascript on your admin page, together with jQuery, and it'll automatically affect all tabular inlines. Optionally, also include jQuery UI Sortable and an Integer field in your inline model named "position" (or whatever you set "position_field" to), which will automatically hide the position field and enable drag-n-drop sorting. **Developed for:** * jQuery 1.3.2 * jQuery UI 1.7.1 * Django trunk (tested in Django v1.0.2) * (Might work with other versions with or without adjustments, but not tested) **Settings (in top of javascript):** * "position_field" is the name of an integer model field that is used for ordering the inline model. If left empty or not found, the drag-n-drop functionality is dropped. Defaults to "position". * "add_link_html" for custom look of "add"-buttons. Defaults to Django's built-in "+" image icon. * "delete_link_html" for custom look of "delete"-buttons. Defaults to Django's built-in "x" image icon. **Use example: ** *admin.py:* class NameInline(admin.TabularInline): model = Name extra = 1 class PersonAdmin(admin.ModelAdmin): inlines = [NameInline] class Media: js = ['js/jquery-1.3.2.min.js', 'js/ui/ui.core.js', 'js/ui/ui.sortable.js', 'js/dynamic_inlines_with_sort.js',] css = { 'all' : ['css/dynamic_inlines_with_sort.css'], } admin.site.register(Person, PersonAdmin) *models.py:* class Person(models.Model): year_born = models.PositiveIntegerField(_('year born'), null=True, blank=True) class Name(models.Model): profile = models.ForeignKey(Profile, verbose_name=_('profile')) position = models.PositiveIntegerField(_('position'), default=0) name = models.CharField(_('name'), max_length=100) class Meta: ordering = ('position',) *dynamic_inlines_with_sort.css:* /* To make row height of saved items same as others */ .inline-group .tabular tr.has_original td { padding-top:0.5em; } .inline-group .tabular tr.has_original td.original p { display:none; } Please post bugs in comments.

  • javascript
  • dynamic
  • admin
  • sort
  • jquery
  • ordering
  • inlines
  • inline
  • tabular
  • sortable
Read More

Template tag to sort a list of links

Sorts a list of HTML anchor tags based on the anchor's contents. This is useful, for example, when combining a static list of links with a dynamic list that needs to be sorted alphabetically. It ignores all attributes of the HTML anchor. {% load anchorsort %} {% anchorsort %} <a href="afoo.jpg">Trip to Fiji</a> <a href="bfoo.jpg">Doe, a deer, a female deer!</a> {% for link in links %} <a class="extra" href="{{ link.href|escape }}">{{ link.name|escape }}</a> {% endfor %} {% endanchorsort %} Note that case (capital vs. lower) is ignored. Any HTMl within the node itself **will not be removed**, so sorting `<a>Bar</a><a><strong>Foo</strong><a/>` will sort as `<a><strong>Foo</strong></a><a>Bar</a>` because `<` is logically less than `b`.

  • template
  • sort
  • anchor
  • a
Read More

Sort Table Headers

Handles creation of `order_by` criteria based on GET parameters and provides context variables to be used when generating table header sort links which respect the current sort field and direction, reversing the direction when the same header is sorted by again. Sample view: from somewhere import SortHeaders from django.contrib.auth.models import User from django.shortcuts import render_to_response LIST_HEADERS = ( ('Username', 'username'), ('First Name', 'first_name'), ('Last Name', 'last_name'), ('Email', None), ) def user_list(request): sort_headers = SortHeaders(request, LIST_HEADERS) users = User.objects.order_by(sort_headers.get_order_by()) return render_to_response('users/user_list.html', { 'users': users, 'headers': list(sort_headers.headers()), }) Sample template: {% load my_tags %} <table cellspacing="0"> <thead> <tr> {% table_header headers %} </tr> </thead> <tbody> {% for user in users %}<tr class="{% cycle odd,even %}"> <td><a href="{{ user.get_absolute_url|escape }}">{{ user.username|escape }}</a></td> <td>{{ user.first_name|escape }}</td> <td>{{ user.last_name|escape }}</td> <td>{{ user.email|escape }}</td> </tr> {% endfor %} </tbody> </table> Sample inclusion tag: from django import template def table_header(context, headers): return { 'headers': headers, } register = template.Library() register.inclusion_tag('table_header.html', takes_context=True)(table_header) Sample inclusion tag template: {% for header in headers %}<th{{ header.class_attr }}> {% if header.sortable %}<a href="{{ header.url|escape }}">{% endif %} {{ header.text }} {% if header.sortable %}</a>{% endif %} </th>{% endfor %}

  • sort
  • table
  • headers
Read More

9 snippets posted so far.