Texas Texas - 8 days ago 4
Python Question

Using Django and Jquery

In addition to this post https://stackoverflow.com/a/17732956 I want to change the order of a list via drag'n'drop and save it afterwards in django backend.

For test purposes and comprehension I've used following fiddle:


and updated the action of the form with my own action. So, instead of script.php, I used action="{% url 'save_order' %}".

In views my function looks like:

def save_order(request):
if (request.method == 'POST'):
list = request.POST['listCSV']

Basically I want to change the order of list elements and save it afterwards with the result that after refreshing the page the saved order is given. However I do not know, how pass vars from jquery to django site. When I change the order, I have the sorted list in 'listCSV'. How do I pass this result to django site to save it in db?

If //$("#listsaveform").submit(); is not commented out and I fire this function referenced with my save_order function, I got this error:

jquery-1.10.2.min.js:6 POST http://localhost:8000/overview/saveOrder/ 405 (Method Not Allowed)


Okay, thanks for the hint. I have never worked with ajax and therefore I'm stucking a bit.
I have my list construct:

{% if habits %}
<ul id="sortable">
{% for habit in habits|dictsort:"priority" %}
<li class="ui-state-default">{{habit.title}}</li>
{% endfor %}
{% endif %}

and this list construct is sortable with this lines of code:

$(function() {
$( "#sortable" ).sortable();

How does look my form?


Here is my solution based on https://impythonist.wordpress.com/2015/06/16/django-with-ajax-a-modern-client-server-communication-practise/.


// Sort & save order of habits
$(function () {
        handle: 'button',
        cancel: '',
        update: function(event, ui) {
          var result = $(this).sortable( "serialize", {key: event.target.id});
          // alert(result);

          var csrftoken = getCookie('csrftoken');

                  url : "/overview/saveOrder/", // the endpoint,commonly same url
                  type : "POST", // http method
                  data : { csrfmiddlewaretoken : csrftoken,
                  result : result,
          }, // data sent with the post request

          // handle a successful response
          success : function(json) {
               console.log(json); // another sanity check
               //On success show the data posted to server as a message

              //  alert('Your list '+json['result']);

          // handle a non-successful response
          error : function(xhr,errmsg,err) {
          console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console


    // var sorted = $( ".selector" ).sortable( "serialize", { key: "sort" } );
    // console.log(sorted)

//For getting CSRF token
function getCookie(name) {
       var cookieValue = null;
       if (document.cookie && document.cookie != '') {
         var cookies = document.cookie.split(';');
         for (var i = 0; i < cookies.length; i++) {
         var cookie = jQuery.trim(cookies[i]);
         // Does this cookie string begin with the name we want?
         if (cookie.substring(0, name.length + 1) == (name + '=')) {
             cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
 return cookieValue;

and on Django side

def save_habit(request):
if (request.method == 'POST'):
    if request.is_ajax():

        habits = Habit.objects.filter(created_by=request.user.userprofile, is_active=True)

        habit_title = request.POST.get('habit_title')
        habit_trigger = request.POST.get('habit_trigger')
        habit_routine = request.POST.get('habit_routine')
        habit_targetbehavior = request.POST.get('habit_targetbehavior')
        habit_image = request.POST.get('habit_image')

        image = habit_image.split('http://localhost:8000/media')
        # TODO: was,  wenn routine noch gar nicht existiert? --> speichern
        obj_routine = Existingroutine.objects.get(name=habit_routine)
        obj_targetbehavior = Targetbehavior.objects.get(name=habit_targetbehavior)

        for habit in habits:
            habit.priority += 1;
            # habit.save();

        habit = Habit(created_by=request.user.userprofile, is_active=True,
        title=habit_title, trigger=habit_trigger, existingroutine=obj_routine,
        targetbehavior=obj_targetbehavior, image=image[1])


        data = {"habit_title":habit_title,
                "habit_targetbehavior":habit_targetbehavior };
        return JsonResponse(data)
return redirect('display_habits')