/*
Sometimes it can be time consuming to go through a bunch of objects in Django's
Admin if you only need to update one field in each. An example of this is an
`order` field that allows you to manually set the order for a queryset.
This snippet contains examples of how to set up the Admin list_display to
make Ajax calls to a custom view (uses jQuery).
The following code may not be worthy of being a snippet, it's all pretty
straightforward, but here it is for those who just want to copy-and-paste.
Here is an example of the order field mentioned above::
order = models.IntegerField(
blank=True, null=True,
help_text="""This field determines the order that products appear on
the site. Enter any number, it does not matter what the number is, only
that it is sequential compared to other products on the site. It is
recommened that you use large numbers such as 100 and 200 to allow room
for additional products or easy reordering in the future."""
)
In your `models.py` add the following `order_helper` method to your
`list_display` [1]_. This will make elements show up::
def order_helper(self):
return u'''''' % (self.id, self.order)
order_helper.allow_tags = True
.. [1] http://www.djangoproject.com/documentation/model-api/#list-display
Put the following jQuery somewhere that gets executed. This will color the
input boxes if the change succeeded or failed::
*/
$(document).ready(function() {
$('.order-helper').css("margin", "0");
$('.order-helper').blur(function(){
var input = $(this);
$.ajax({
url: "./"+ input.attr('name') +"/order/",
data: order=input.attr('value'),
type: "POST",
complete: function(xhr_obj, msg){
if (msg == 'success') {
input.css("border", "1px solid green");
} else {
input.css("border", "1px solid red");
}
},
});
});
});
/*
Make a custom view somewhere to recieve the Ajax POST::
@login_required
@require_POST
def order_helper(request, prod_id):
prod = get_object_or_404(Product, id=prod_id)
prod.order = request.POST.get('order')
prod.save()
return HttpResponse(content='Ok', status=200)
In your `urls.py` add a call to your new view. (If you use the same /admin/...
URL scheme as this example does, it must be *above* your regular Admin URLconf
include statement.)::
url(r'^admin/products/product/(?P\d+)/order/$',
'path.to.order_helper'),
*/