[Django]-Drag and drop ordering of formset with extra entries

3đź‘Ť

âś…

I found my own solution. The snippet was setting the order for every row that had a non-empty primary key value. But the extra rows have an empty primary key, and I believe they have to stay empty for Django to know that they are to be inserted instead of updated. I modified the function to check for the other fields being empty (fortunately, I only have a couple) as well as the primary key:

jQuery(function($) {
    $('div.inline-group').sortable({
        items: 'div.inline-related',
        handle: 'h3:first',
        update: function() {
            $(this).find('div.inline-related').each(function(i) {
                if ($(this).find('input[id$=chair_id]').val() ||
                  $(this).find('select[id$=member]').val() ||
                      $(this).find('select[id$=description]').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();
});

This did the trick for me. I could maybe improve it by adding a hidden field to the form that gets set whenever any field on a row gets modified. But at this point I’m still a jQuery n00b, so this will do. If anybody has better ideas, feel free to comment or add another answer.

👤Fred Larson

1đź‘Ť

I do sortable formsets in one of my apps. I use this jQuery drag and drop plugin:

http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/

I bind the plugin’s onDrop event to a function that resets the value of all “order” fields.

Additionally, I pass initial data to the formset so the formset’s extra “order” fields always have a value in cases where there is no javascript available – the user won’t be able to re-order rows, but they can edit and post changes without the null error you described.

👤Harold

Leave a comment