An easy way of making inlines orderable using drag-and-drop, using jQuery UI's sortable() plugin.
First, add an "order" field to the inline models which is an IntegerField, and set that model to use 'order' as its default order_by.
Then hook in the JavaScript. This should make them drag-and-drop sortable using jQuery UI, and also hide the divs containing those order fields once the page has loaded. This technique is unobtrusive: if JavaScript is disabled, the order fields will be visible and the user will be able to manually set the order by entering numbers themselves.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | # models.py
from django.db import models
class Menu(models.Model):
name = models.CharField(max_length = 100)
def __unicode__(self):
return self.name
class Item(models.Model):
menu = models.ForeignKey(Menu)
name = models.CharField(max_length = 100)
url = models.CharField(max_length = 100)
order = models.IntegerField(blank = True, null = True)
def __unicode__(self):
return self.name
class Meta:
ordering = ('order',)
# admin.py
from django.contrib import admin
from django import forms
from models import Menu, Item
class MenuForm(forms.ModelForm):
model = Menu
class Media:
js = (
'/static/js/jquery-latest.js',
'/static/js/ui.base.js',
'/static/js/ui.sortable.js',
'/static/js/menu-sort.js',
)
class ItemInline(admin.StackedInline):
model = Item
admin.site.register(Menu,
inlines = [ItemInline],
form = MenuForm,
)
"""
/* menu-sort.js */
jQuery(function($) {
$('div.inline-group').sortable({
/*containment: 'parent',
zindex: 10, */
items: 'div.inline-related',
handle: 'h3:first',
update: function() {
$(this).find('div.inline-related').each(function(i) {
if ($(this).find('input[id$=name]').val()) {
$(this).find('input[id$=order]').val(i+1);
}
});
}
});
$('div.inline-related h3').css('cursor', 'move');
$('div.inline-related').find('input[id$=order]').parent('div').hide();
});
"""
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Great presentation at PyCon UK 2008 this morning Simon. I have been wondering how do this for a year!
#
Nice! Just a note for anyone who was confused like I was - the JavaScript only works on StackedInlines, not TabularInlines.
#
ordering is lost if there´s an error somewhere in the form.
#
If you change line 63 (menu-sort.js) to
and then remove the
if
statement, It's a little less brittle in terms of field names (as it is here it requires aname
field in the inline model.#
This should work for TabularInlines. You might want to tweak my choice of handle and you'll have to change the eq(5) in the last line depending where in the field list you have placed 'order':
#
At first, it looked pretty easy. But, I realized the menu-sort.js was made for an older version of Django.
With django1.02, inline items in the automatic admin look like:
Does anyone already worked on updating menu-sort.js ?
Thank you all
#
The following script works with TabularInline in latest django release:
#
I managed to adapt it. Your critics about this piece of javascript are warmly welcomed!
#
hi! my item model has two ForeignKey fields and ordering is working but when i save the form it rearanges as in initial situation, as no ordering was made after making a few entries. does someone has a hint?
here is my 'Item' class from model.py
class PhotoSetPhotoItem(models.Model): #mid = models.AutoField(primary_key=True) order = models.IntegerField(blank = True, null = True) photo_set = models.ForeignKey('PhotoSet', related_name='photoset') photo_item = models.ForeignKey('Photo', related_name='photoitem') class Meta: #db_table='photoset_photoitems' ordering = ['order']
#
cant make markdown working...
#
for vedran: "name" and "order" are 2 required fields in the original code. Use leplatrem's code (June 26) which only requires "order"
#
The script above doesn't set the order fields properly if the fields are moved before the name has been entered. It's easier to just update the order fields before the form submits like this:
#
thanx a lot!
#
I used leplatrem's June 26 comment but I had to change the first line to this:
jQuery(function($) {
because something else in the page called
jquery.noConflict()
and it was messing up use of the dollar sign.I also had to change
vTextField
tovIntegerField
-- not sure why I had to do this, maybe it has to do with my django version, which is 1.2.0 beta 1And then I also changed this:
$(this).find('input[id$=parent_order]').parent('div').parent('div').hide();
to this:
$(this).find('input[id$=parent_order]').parent('div').parent('div').hide().parent().parent().css('cursor','move');
Which helps the user know that the items are orderable (otherwise there is no indication in the U.I. that the items are orderable).
Here is my final code:
#
replace ALL occurrences of "parent_order" with just "order" in my previous post.
#
A quick hack of eddified's post to work with Django 1.2 and update the order field with dynamic inline creation:
#
I had to modify the following in order to hide the order field in Django 1.2.1.
I changed the line:
to:
#
Please login first before commenting.