Re-ordering entries in a model using drag-and-drop

Question!

Say I have a blogging app in Django. How can i re-order the posts using a draggable table in the default admin?

It would be best if i didn't have to add any extra fields to the model, but if i really have to i can.

By : Josh Hunt


Answers

You may try this snippet https://gist.github.com/barseghyanartur/1ebf927512b18dc2e5be (originally based on this snippet http://djangosnippets.org/snippets/2160/).

Integration is very simple.

Your model (in models.py):

class MyModel(models.Model):
    name = models.CharField(max_length=255)
    order = models.IntegerField()
    # Other fields...

    class Meta:
        ordering = ('order',)

You admin (admin.py):

class MyModelAdmin(admin.ModelAdmin):
    fields = ('name', 'order',) # Add other fields here
    list_display = ('name', 'order',)
    list_editable = ('order',)

    class Media:
        js = (
            '//code.jquery.com/jquery-1.4.2.js',
            '//code.jquery.com/ui/1.8.6/jquery-ui.js',
            'path/to/sortable_list.js',
        )

Change the JS (of the snippet) accordingly if your attributes responsible for holding the name and ordering are named differently in your model.



There's a nice package for ordering admin objects these days

https://github.com/iambrandontaylor/django-admin-sortable

Also, django-suit has builtin support for this



This video can help you solving your question :)
By: admin