首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Django和Jquery

使用Django和Jquery
EN

Stack Overflow用户
提问于 2017-07-06 17:55:35
回答 1查看 161关注 0票数 0

除了这篇文章https://stackoverflow.com/a/17732956,我还想通过拖放来改变列表的顺序,然后保存到django后台。

为了测试目的和理解,我使用了以下小提琴:

http://jsfiddle.net/LvA2z/#&togetherjs=LvHpjIr7L0

并用我自己的操作更新了表单的操作。所以,我用action="{% url 'save_order‘%}“代替了script.php。

在视图中,我的函数如下所示:

代码语言:javascript
运行
复制
def save_order(request):
    if (request.method == 'POST'):
        list = request.POST['listCSV']
        print(list)

基本上,我想更改列表元素的顺序,然后保存它,结果是在刷新页面后,会给出保存的顺序。然而,我不知道如何将变量从jquery传递到django站点。当我改变顺序时,我的排序列表在'listCSV‘中。如何将此结果传递到django站点以将其保存在db中?

编辑:如果//$("#listsaveform").submit();没有被注释掉,并且我触发了由我的save_order函数引用的这个函数,我会得到这样的错误:

jquery-1.10.2.min.js:6 POST http://localhost:8000/overview/saveOrder/ 405 (不允许使用方法)

编辑:

好的,谢谢你的提示。我从来没有使用过ajax,因此我对它有一点不了解。我有我的列表结构:

代码语言:javascript
运行
复制
  {% if habits %}
  <ul id="sortable">
      {% for habit in habits|dictsort:"priority" %}
      <li class="ui-state-default">{{habit.title}}</li>
      {% endfor %}
  </ul>
  {% endif %}

这个列表结构可以用下面这几行代码排序:

代码语言:javascript
运行
复制
  $(function() {
      $( "#sortable" ).sortable();
  });

我的表格看起来怎么样?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-17 21:31:40

这是我基于https://impythonist.wordpress.com/2015/06/16/django-with-ajax-a-modern-client-server-communication-practise/的解决方案。

在JS中

代码语言:javascript
运行
复制
// Sort & save order of habits
$(function () {
    $('.sort').sortable({
        handle: 'button',
        cancel: '',
        update: function(event, ui) {
          var result = $(this).sortable( "serialize", {key: event.target.id});
          // alert(result);

          var csrftoken = getCookie('csrftoken');


          $.ajax({
                  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("FAILURE");
          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));
             break;
          }
     }
 }
 return cookieValue;
}

在Django一边

代码语言:javascript
运行
复制
def save_habit(request):
print('save_habit')
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')
        print(habit_image)

        image = habit_image.split('http://localhost:8000/media')
        print(image[1])
        # 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])

        #habit.save()

        data = {"habit_title":habit_title,
                "habit_trigger":habit_trigger,
                "habit_routine":habit_routine,
                "habit_targetbehavior":habit_targetbehavior };
        return JsonResponse(data)
return redirect('display_habits')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44945620

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档