Login

Django Drag and Drop Using YUI

Author:
veeravendhan
Posted:
April 23, 2009
Language:
JavaScript
Version:
Not specified
Score:
0 (after 0 ratings)

I was trying to implement the django inline drag & drop, I cudn't understand. Then I have try with YUI library Copy the above code in the respective .py & download the YUI library and add the JS in your media folder. This will do...,

Try this our , it's easy to use..,

  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
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
Models.py
# Create your models here.
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',)

---------------------------------------*********--------------------
View.py
from django.shortcuts import render_to_response, get_list_or_404

from dragdrop.ordering.models import *

def dragdropView(request):
    items = Item.objects.all()
    return render_to_response("login.html",{'items':items});

def reorder(request):    
    orderlist = request.POST.get('order','').split('li2_')    
    i = 1
    for each in orderlist:        
        if(len(each) > 1):                    
            if(each[each.rfind(',')+1:len(each)] != ''):
                item = Item.objects.get(name = each[each.rfind(',')+1:len(each)])                
                item.order = i
                item.save()
                i = i+1
    dragdropView(request);

-----------------------------------------
HTML Template --Name is login.html


<script type="text/javascript" src="/static/js/yahoo-dom-event/yahoo-dom-event.js" ></script>
    <script type="text/javascript" src="/static/js/animation/animation-min.js"></script>
    <script type="text/javascript" src="/static/js/dragdrop/dragdrop-min.js" ></script> 
    <script type="text/javascript" src="/static/js/utilities/utilities.js" ></script>  
	

</head>

<style type="text/css">

/*div.workarea { padding:10px; float:left }*/

ul.draglist { 
    position: relative;
    width: 200px; 
    height:240px;
    background: #f7f7f7;
    border: 1px solid gray;
    list-style: none;
    margin:0;
    padding:0;
}

ul.draglist li {
    margin: 1px;
    cursor: move;
    zoom: 1;
}

ul.draglist_alt { 
    position: relative;
    width: 200px; 
    list-style: none;
    margin:0;
    padding:0;
    /*
       The bottom padding provides the cushion that makes the empty 
       list targetable.  Alternatively, we could leave the padding 
       off by default, adding it when we detect that the list is empty.
    */
    padding-bottom:20px;
}

ul.draglist_alt li {
    margin: 1px;
    cursor: move; 
}


li.list1 {
    background-color: #D1E6EC;
    border:1px solid #7EA6B2;
}

li.list2 {
    background-color: #D8D4E2;
    border:1px solid #6B4C86;
}

#user_actions { float: right; }

</style>




<script type="text/javascript">

(function() {

var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var DDM = YAHOO.util.DragDropMgr;

//////////////////////////////////////////////////////////////////////////////
// example app
//////////////////////////////////////////////////////////////////////////////
YAHOO.example.DDApp = {
    init: function() {

        var rows=3,cols=2,i,j;
        for (i=1;i<cols+1;i=i+1) {
            new YAHOO.util.DDTarget("ul"+i);
        }

        for (i=1;i<cols+1;i=i+1) {
            for (j=1;j<rows+1;j=j+1) {
                new YAHOO.example.DDList("li" + i + "_" + j);
            }
        }

        Event.on("showButton", "click", this.showOrder);
        Event.on("switchButton", "click", this.switchStyles);
    },

    showOrder: function() {
        var parseList = function(ul, title) {
            var items = ul.getElementsByTagName("li");
            //var out = title + ": ";
            var out = "";
            for (i=0;i<items.length;i=i+1) {
                out += items[i].id + ","+items[i].title;
            }
            return out;
        };

        var ul1=Dom.get("ul1"), ul2=Dom.get("ul2");
        //alert(parseList(ul1, "List 1") + "\n" + parseList(ul2, "List 2"));
		  return parseList(ul2, "List 2");
    },

    switchStyles: function() {
        Dom.get("ul1").className = "draglist_alt";
        Dom.get("ul2").className = "draglist_alt";
    }
};

//////////////////////////////////////////////////////////////////////////////
// custom drag and drop implementation
//////////////////////////////////////////////////////////////////////////////

YAHOO.example.DDList = function(id, sGroup, config) {

    YAHOO.example.DDList.superclass.constructor.call(this, id, sGroup, config);

    this.logger = this.logger || YAHOO;
    var el = this.getDragEl();
    Dom.setStyle(el, "opacity", 0.67); // The proxy is slightly transparent

    this.goingUp = false;
    this.lastY = 0;
};

YAHOO.extend(YAHOO.example.DDList, YAHOO.util.DDProxy, {

    startDrag: function(x, y) {
        this.logger.log(this.id + " startDrag");

        // make the proxy look like the source element
        var dragEl = this.getDragEl();
        var clickEl = this.getEl();
        Dom.setStyle(clickEl, "visibility", "hidden");

        dragEl.innerHTML = clickEl.innerHTML;

        Dom.setStyle(dragEl, "color", Dom.getStyle(clickEl, "color"));
        Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
        Dom.setStyle(dragEl, "border", "2px solid gray");
    },

    endDrag: function(e) {

        var srcEl = this.getEl();
        var proxy = this.getDragEl();

        // Show the proxy element and animate it to the src element's location
        Dom.setStyle(proxy, "visibility", "");
        var a = new YAHOO.util.Motion( 
            proxy, { 
                points: { 
                    to: Dom.getXY(srcEl)
                }
            }, 
            0.2, 
            YAHOO.util.Easing.easeOut 
        )
        var proxyid = proxy.id;
        var thisid = this.id;

        // Hide the proxy and show the source element when finished with the animation
        a.onComplete.subscribe(function() {
                Dom.setStyle(proxyid, "visibility", "hidden");
                Dom.setStyle(thisid, "visibility", "");
            });
        a.animate();
    },

    onDragDrop: function(e, id) {

        // If there is one drop interaction, the li was dropped either on the list,
        // or it was dropped on the current location of the source element.
        if (DDM.interactionInfo.drop.length === 1) {

            // The position of the cursor at the time of the drop (YAHOO.util.Point)
            var pt = DDM.interactionInfo.point; 

            // The region occupied by the source element at the time of the drop
            var region = DDM.interactionInfo.sourceRegion; 

            // Check to see if we are over the source element's location.  We will
            // append to the bottom of the list once we are sure it was a drop in
            // the negative space (the area of the list without any list items)
            if (!region.intersect(pt)) {
                var destEl = Dom.get(id);
                var destDD = DDM.getDDById(id);
                destEl.appendChild(this.getEl());
                destDD.isEmpty = false;
                DDM.refreshCache();                
            }
            var obj = YAHOO.example.DDApp.showOrder();
            //alert(obj);
            YAHOO.util.Connect.setDefaultPostHeader(false);
            YAHOO.util.Connect.asyncRequest("POST", "../reorder/", callback, "order="+obj);
				            

        }
    },

    onDrag: function(e) {

        // Keep track of the direction of the drag for use during onDragOver
        var y = Event.getPageY(e);

        if (y < this.lastY) {
            this.goingUp = true;
        } else if (y > this.lastY) {
            this.goingUp = false;
        }

        this.lastY = y;
    },

    onDragOver: function(e, id) {
    
        var srcEl = this.getEl();
        var destEl = Dom.get(id);

        // We are only concerned with list items, we ignore the dragover
        // notifications for the list.
        if (destEl.nodeName.toLowerCase() == "li") {
            var orig_p = srcEl.parentNode;
            var p = destEl.parentNode;

            if (this.goingUp) {
                p.insertBefore(srcEl, destEl); // insert above
            } else {
                p.insertBefore(srcEl, destEl.nextSibling); // insert below
            }

            DDM.refreshCache();
        }
    }
});

Event.onDOMReady(YAHOO.example.DDApp.init, YAHOO.example.DDApp, true);

})();

var callback = {
  success: function() { /*alert("OK");*/ },
  failure: function(response) { /*alert("Failure occured. " + response.status);*/ }
}

</script>




<body style="vertical-align: middle; height: 100%;" class="login-bg">   
    
    <div class="workarea">
 <!--  <h3>List 1</h3>
  <ul id="ul1" class="draglist">
    <li class="list1" id="li1_1">list 1, item 1</li>
    <li class="list1" id="li1_2">list 1, item 2</li>
    <li class="list1" id="li1_3">list 1, item 3</li>
  </ul> -->
</div>
<div class="workarea">
  <ul id="ul2" class="draglist" >
  <li	></li>
  {% for each in items%}  
  <li class="list2" id="li2_{{each.order}}" title= "{{each.name}}" ><div>{{ forloop.counter}} <table><tr><td>{{each.name}}</td></tr></table> </div></li>
  {% endfor %}
  </ul>
</div>
<!-- <div id="user_actions">
  <input type="button" id="showButton" value="Show Current Order" />
  <input type="button" id="switchButton" value="Remove List Background" />
</div> -->
</body>

</html>


-------------------------------------------------------
Fixures

[

    {
	"model": "ordering.Menu",
	"pk": 1,
	"fields": {
		"name": "Project Management"
	}
    },

    {
	"model": "ordering.Menu",
	"pk": 2,
	"fields": {
		"name": "E-Mail"
	}
    },

    {
	"model": "ordering.Item",
	"pk": 1,
	"fields": {
		"menu": "1",
		"name": "First",
		"url": "abc.com",
		"order":"1"
	}
    },
    {
	"model": "ordering.Item",
	"pk": 2,
	"fields": {
		"menu": "1",
		"name": "Second",
		"url": "abc.com",
		"order":"2"
	}
    },
    {
	"model": "ordering.Item",
	"pk": 3,
	"fields": {
		"menu": "1",
		"name": "Third",
		"url": "abc.com",
		"order":"3"
	}
    }
]

----------------------------------------------------------------
DownLoad this from YUI- Library: 
Copy these folders from build directory of YUI library.

1. animation
2. dragdrop
3. utilities
4. yahoo-dom-event

------------------------- This will work fine -----------------

More like this

  1. Django Collapsed Stacked Inlines by applecat 1 year, 9 months ago
  2. Django Collapsed Stacked Inlines by mkarajohn 3 years, 10 months ago
  3. Dynamically adding forms to a formset. OOP version. by halfnibble 9 years, 6 months ago
  4. Convert multiple select for m2m to multiple checkboxes in django admin form by abidibo 11 years, 7 months ago
  5. Django admin inline ordering - javascript only implementation by ojhilt 11 years, 11 months ago

Comments

Please login first before commenting.