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();
});
"""
|
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.
#
Nice and simple! I have implemented reordering in my project sorl-curetor where you can also reorder in groups with respect to another field.
#
ordering is lost if there“s an error somewhere in the form.
#