Code Monkey home page Code Monkey logo

django-inline-ordering's Introduction

django-inline-ordering

This app aims at easing implementing drag & drop reordering of inline data in Django Admin.

Recent version of Grappelli includes drag and drop inlines, so if you are already using Grappelli, installing django-inline-ordering does not make sense. If you didn't evaluate Grappelli yet, I encourage you to do so!

The django-inline-ordering is being tested during development on:

  • Firefox 3.5+
  • Internet Explorer 7+
  • Google Chrome 10+
  • Opera 11+

This app is unlikely to be further developed, however I'm planning to release a successor library for Django 1.4+ in future.

Installation

  1. Put 'inline_ordering' on your python path
  2. Add 'inline_ordering' to INSTALLED_APPS tuple in settings file

Usage

For each model that you want to be reorderable with drag & drop, you need to setup an admin class and slightly modify model declaration. This way you can easily apply reordering to existing model classes. You'll also have to run collectstatic task or copy one file to your MEDIA_ROOT when using Django < 1.3.

Let's start with a simple example: Gallery has many Images. User might want to reorder the photos in the gallery to fit his likings.

  1. Setup your admin inline class to inherit after OrderableStackedInline

    from inline_ordering.admin import OrderableStackedInline
    
    
    class ImageInline(OrderableStackedInline):
    
      model = Image
    
    
    class GalleryAdmin(ModelAdmin):
    
        model = Gallery
        inlines = (ImageInline, )
    
  2. Setup your model to inherit after Orderable

    from inline_ordering.models import Orderable
    
    class Image(Orderable):
      src = models.ImageField(upload_to='gallery/images')
      title = models.CharField(max_length=255)
      alt = models.TextField()
    
    class Meta(Orderable.Meta):
      pass
    

    As ordering column was named inline_ordering_position, avoid using this name in your model.

    The Meta class declaration is NOT necessary - add it only if you need to set your own meta attributes.

  3. Make inline_ordering.js accessible over HTTP

    Since Django 1.3, there is a staticfiles app that django-inline-ordering is aware of. Just run manage.py collectstatic to copy/symlink media files.

    The simplest way, back in Django 1.2, was to copy media/inline_ordering.js to your MEDIA_ROOT.

    If you however believe that would make a mess, take advantage of the 'INLINE_ORDERING_JS' setting and set it to a location which should be requested when accessing orderable inlines:

    INLINE_ORDERING_JS = STATIC_URL + '/js/third_party/inline_ordering.js'

Known issues

  1. Reordering won't work for new records until saved. This needs a onchange handler for the record form or some model refactoring.
  2. At this point there is no support for tabular inlines. If you would like to approach this problem, fork the project on Github.

Development

A simple test project has been added in fdc2189 under tests/testproject. Use tools/buildenv.sh to build a virtualenv for development and syncdb to create necessary models and admin permissions.

Version 1.0.3 is likely to be the last one, as I'm planning to release a new library to support ordering in Django admin both of inlines as well as on the change list.

Kudos

simon for http://djangosnippets.org/snippets/1053/

django-inline-ordering's People

Contributors

anvio avatar lacrymology avatar mikeedwards avatar piotrkilczuk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

django-inline-ordering's Issues

Draggable not working out of the box

It required following changes in order to work in Fx 3.6.12 on Ubuntu (not tested on other browsers though)

    //jQuery("div.inline-group").disableSelection();
    jQuery('div.inline_ordering_position').hide();

General behavior bugs

Originally reported by e-mail by Frederico C. (thanks!)

I tried your app but it didn't work out of the box. I had to change the init function to:

init: function(){
    jQuery("div.inline-group").sortable({
        axis: 'y',
        placeholder: 'ui-state-highlight',
        forcePlaceholderSize: 'true',
        items: InlineOrdering.getOrderables(),
        start: function(){ jQuery(this).css('min-height', jQuery(this).height()) },
        update: function(){ InlineOrdering.update() }
    });
    jQuery("div.inline-group").disableSelection();

    jQuery(this).find('div.inline_ordering_position').hide();
    jQuery('.add-row a').click(function(){
        InlineOrdering.update
    });
},

Note also the add of the start event, that prevents a very annoying behavior in google chrome (the div shrinks in height and everything moves - very annoying).

You also need to add a bit of css:

/* custom.css */
.ui-sortable{ cursor: move }

.inline_ordering_position{ display: none }

and this is what I've done in admin.py - note the css dictionary:

from django.contrib.admin import StackedInline
from settings import ADMIN_MEDIA_PREFIX

class OrderableStackedInline(StackedInline):

"""Adds necessary media files to regular Django StackedInline"""

class Media:
    js = (
          '%sjs/jquery-ui.js' % ADMIN_MEDIA_PREFIX, 
          '%sjs/inline_ordering.js' % ADMIN_MEDIA_PREFIX,
    )
    css = {
        'screen': ('%scss/custom.css' % ADMIN_MEDIA_PREFIX,) 
    }

There is a problem on the save

I order the items in the admin, but when I save the order is loaded back to the sorting before my "hand ordering". I guess there is a problem on the save function.

Some ideas by Martin

Pasted from em@il -- thx for reporting...

var InlineOrdering = {

    /**
     * Get list of elements that can be reordered
     *
     * At this point, only already existent records can be reordered (ie. where pk != '')
     *
     * @return Array
     * @todo Check if given record changed, and if so, make it reorderable
     * @todo Primary key might not be 'id' - better selector needed
     *
     */
    getOrderables: function(){
    return jQuery('div.inline-group .inline-related input[name$=id]:not([value=])').parent('.inline-related');
    },

    /**
     * Inits the jQuery UI D&D
     *
     */
    init: function(){
    jQuery("div.inline-group").sortable({
        axis: 'y',
        placeholder: 'ui-state-highlight',
        forcePlaceholderSize: 'true',
        items: InlineOrdering.getOrderables(),
        update: InlineOrdering.update
    });
    jQuery("div.inline-group").disableSelection();

    jQuery(this).find('div.position').hide();
    jQuery('.add-row a').click(InlineOrdering.update);

    /**
     * Hiding all position labels/inputs.
     */
    $('input[id$=position]').hide().parent().hide();

    /**
     * Adding the drag-cursor to the inline rows (parent + all children which are not <img>, <a> or <select>)
     * with non-empty <select>-fields.
     */
    var nonEmptyRows = $('div[class$=position]').find("select[value!='']").parent();
    nonEmptyRows.parent().css('cursor','move');
    nonEmptyRows.find('*').not('select, img, a').css('cursor','move');
    InlineOrdering.update();//Call update for initial numbering
    },

    /**
     * Updates the position field
     *
     */
    update: function(){
    InlineOrdering.getOrderables().each(function(i){
        jQuery(this).find('input[id$=position]').val(i + 1);

            /**
            * Numberizes the list starting with 1., 2. ... 
            */
        j = i + 1;

        var label = $('div[class$=position]').find("select[value!='']").parent().children(':first-child')[i].innerHTML;
        label = label[0].match(/\d+/) ? j + label.substr(1) : j + '. ' + label

        $('div[class$=position]').find("select[value!='']").parent().children(':first-child')[i].innerHTML = label;
    });
    }

};

jQuery(function(){
    InlineOrdering.init();
});

README: Name in INSTALLED_APPS

Right now the README says:
"Add 'inline-ordering' to INSTALLED_APPS tuple in settings file"

I think it should be 'inline_ordering'. It won't work otherwise.

jQuery conflict

TypeError: 'undefined' is not a function (evaluating 'InlineOrdering.jQuery("div.inline-group").sortable')

Is there a way of eliminating this issue?

Wrong positions after deleting inline instances

I found using Max() to determine the next position will bring in wrong values as soon as an instance with a position < Max() is deleted. Those gaps will not be closed by moving the existing ones one position back.
Therefore I'm doing the saving like this in the ModelAdmin (no custom save() method in the model itself anymore) :

class OrderableAdmin(admin.ModelAdmin):
def save_formset(self, request, form, formset, change):

    instances = formset.save(commit = False)
    nextPos = len(formset.queryset)

    for i in instances:

        if i.inline_ordering_position == None:
            i.inline_ordering_position = nextPos
            nextPos += 1

        i.save()


    formset.save_m2m()

PyPi Update Needed

The distro on PyPi is still using the version with the /media/ directory instead of /static/. Using pip install django-inline-ordering leaves Django 1.3+ unable to collect the static file.

Jquery UI is not present in the admin interface!

Is necessary to add by hand the jquery UI to base.html. I used this code

<script>(function($){jQuery = $.noConflict(true);})(django.jQuery);</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js"></script>

Does not work with a ManyToMany relationship

This plugin only appears to work if you have a one-to-many (ForeignKey) relationship between Gallery and Images.

What if you have many Images that you use across different Gallerys (ie. a many-to-many field?). Using your example of Images and Gallery.

This will work:

class Gallery(models.Model):
    images = ForeignKey(Image)

This won't:

class Gallery(models.Model):
    images = ManyToManyField(Image)

I have the second setup, and I get the following error when implementing your code:

<class 'appname.models.Image'> has no ForeignKey to <class 'appname.models.Gallery'>

Maybe I have it set up incorrectly, but I followed your steps exactly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.