如何在jQuery自动保存中使用django视图? [英] How to use django view with jquery autosave?

查看:56
本文介绍了如何在jQuery自动保存中使用django视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面上显示的表单集很长.当前保存如下:

if request.method == 'POST':

    survey_formset = SurveyFormset(request.POST)

    if survey_formset.is_valid():
        ss = SurveySet()
        ss.user=request.user
        ss.save()
        for form in survey_formset.forms:
            saved = form.save(commit=False)
            saved.surveyset = ss
            saved.save()
        return HttpResponseRedirect('/')

如何做到这一点,以便每次用户填写另一个输入时整个调查集都保存在后台?

到目前为止,这是我到目前为止所拥有的.如何使用回调通过AJAX将内容发送到服务器?

    <form action="" method="POST" id="surveyset">{% csrf_token %}
        {{ survey_formset.management_form|crispy }}

        <!--  A lot of inputs!  -->

          {% for form in survey_formset.forms %}
              <hr>
              <div id="survey-{{ forloop.counter }}" class='content'>
                {% crispy form %}
              </div>
          {% endfor %}

        <input id='save_set' type="submit" value="Submit" class='button' />
    </form>

<!-- Time to autosave! -->

<script type="text/javascript" src="{% static "js/jquery.autosave.js" %}"></script>
<script> 
    $(document).ready( function() {

      $("form").autosave({
        callbacks: {
          trigger: ["change", function() {
            var self = this;

            $("#save_set").click(function() {
              self.save();
            });

          }],
          save: {
            method: "ajax",

            // What do I tell the django view? 
            // How do I silently save in the background?

            options: {
              success: function() {
                console.log("saved!");
              }
            }
          }
        }
      });

    }); 
</script>

我正在使用此人代码:

https://github.com/nervetattoo/jquery-autosave

解决方案

Django提供了一个方便的 jQuery.ajax(),因此默认情况下将发送此邮件.

请确保您选择其中一个:

或:

您可以在视图中使用它来创建它的一部分,以适当地处理AJAX请求:

if request.is_ajax():
    # TODO: Handle autosave plugin save requests
    pass
 else:
    # this is where the normal stuff you already have happens
    ...

使用自动保存插件,保存回调与jQuery的AJAX方法具有相同的选项.一个典型的设置如下所示:

{ url: "http://yourdomain.com/your-view",
  data: {"key_for_server1": var1, "key_for_server2": var2},
  success: function() { 
            // pop up a nice green 'Saved!' message 
  },
  error: function() { 
            // alert "Oh, no! It didn't work!" 
  }
}

您可以在上面链接的文档中详细设置很多选项,而autosave插件将它们直接传递给您,以便您可以一视同仁.

上面的主要数据是url要将数据发送到的内容(对于您的视图来说,在urls.py中是什么),data是要发送的实际的POST数据(后来在request.post dict),以及successcompleteerror回调,它们是处理相应条件的函数.

请注意,它将基于服务器响应的HTTP状态代码来考虑成功或失败.因此,例如,如果您raise Http404(不要-仅作为示例),它将调用error,但是如果您返回普通的HttpResponse(通常是JSON),它将调用success.

I have a very long formset that is displayed to the page. It is currently saved like so:

if request.method == 'POST':

    survey_formset = SurveyFormset(request.POST)

    if survey_formset.is_valid():
        ss = SurveySet()
        ss.user=request.user
        ss.save()
        for form in survey_formset.forms:
            saved = form.save(commit=False)
            saved.surveyset = ss
            saved.save()
        return HttpResponseRedirect('/')

How can I make it so the entire surveyset gets saved in the background every time the user fills in another input?

So far this what I have so far. How do I use callbacks to send stuff to the server via AJAX?

    <form action="" method="POST" id="surveyset">{% csrf_token %}
        {{ survey_formset.management_form|crispy }}

        <!--  A lot of inputs!  -->

          {% for form in survey_formset.forms %}
              <hr>
              <div id="survey-{{ forloop.counter }}" class='content'>
                {% crispy form %}
              </div>
          {% endfor %}

        <input id='save_set' type="submit" value="Submit" class='button' />
    </form>

<!-- Time to autosave! -->

<script type="text/javascript" src="{% static "js/jquery.autosave.js" %}"></script>
<script> 
    $(document).ready( function() {

      $("form").autosave({
        callbacks: {
          trigger: ["change", function() {
            var self = this;

            $("#save_set").click(function() {
              self.save();
            });

          }],
          save: {
            method: "ajax",

            // What do I tell the django view? 
            // How do I silently save in the background?

            options: {
              success: function() {
                console.log("saved!");
              }
            }
          }
        }
      });

    }); 
</script>

I am using this guys code:

https://github.com/nervetattoo/jquery-autosave

解决方案

Django provides a handy is_ajax method on its HttpRequest objects that tells you whether the HTTP_X_REQUESTED_WITH header was set. Since the autosave plugin uses jQuery.ajax(), it will send this by default.

Just make sure you either:

or:

  • Use the csrf_exempt decorator on your view. (This is not recommended usually and should be used with caution.)

You can use this in your view to create a part of it that will handle the AJAX requests appropriately:

if request.is_ajax():
    # TODO: Handle autosave plugin save requests
    pass
 else:
    # this is where the normal stuff you already have happens
    ...

With the autosave plugin, the save callback takes the same options as jQuery's AJAX method. A typical setup looks like this:

{ url: "http://yourdomain.com/your-view",
  data: {"key_for_server1": var1, "key_for_server2": var2},
  success: function() { 
            // pop up a nice green 'Saved!' message 
  },
  error: function() { 
            // alert "Oh, no! It didn't work!" 
  }
}

There are a ton of options you can set detailed in the documentation I linked above, and the autosave plugin passes them straight through so you can tell it all the same things.

The main ones, above, are the url to send data to (whatever is in urls.py for your view), data which is the actual POST data you will send (later found in the request.post dict), and the success, complete, and error callbacks, which are functions that handle those respective conditions.

Note that it will consider a success or failure based on the HTTP status code of the server response. So, e.g., if you raise Http404 (don't -- just an example) it would call error, but if you return a normal HttpResponse (normally JSON) it will call success.

这篇关于如何在jQuery自动保存中使用django视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆