简体   繁体   English

如何将localStorage数据提交给Django?

[英]How can I submit localStorage data to Django?

I have data in localStorage,and I want to submit it along with userid to Django through POST request. 我在localStorage中有数据,我想通过POST请求将其与用户ID一起提交给Django。 How do I make this work? 我该如何工作?

1) Send Ajax request: it requires csrf token and I can't make it valid. 1)发送Ajax请求:它需要csrf令牌,而我不能使其有效。

  function submitData() {
  // send result to server
    var data = localStorage.getItem("groups");
    var userid = {{user.userid}};
    console.log(data);

    $.ajax({
      url:"/interface/submit/",
      type:"POST",
      data: { group:data,
              userid:userid,
              csrfmiddlewaretoken: '{{ csrf_token }}'},
      success:function() {
        alert("Submitted succeffully");
        window.location = "/interface/";
      }
    })
  }

2) Use Django forms: for now i can only grab information from the field, not localStorage. 2)使用Django表单:目前,我只能从该字段中获取信息,而不能从localStorage中获取信息。

  <form action="/interface/submit/" method="post">
    {% csrf_token %}
    <input type="submit" value="Submit">
  </form>

Error when using the 1st approach: 使用第一种方法时出错:

Request information 索取资料

GET
Variable    Value
csrfmiddlewaretoken 
u'{{ csrf_token }}'
group   
u'371,197,220,306,213,328,399,373,283,end,371,197,220,306,213,328,399,373,283,end,371,197,220,end,'
POST
No POST data
FILES
No FILES data
COOKIES
Variable    Value
csrftoken   
'F8jc4jObrxI2bQ6Y3CgCiuf6MTOpf2Uo'
sessionid   
'8uvrhe9yytpam38h5xb4tnvz8ijiui4p'

Regarding 1) is your template rendering a form with {% csrf_token %} where you use your ajax code? 关于1)您的模板是否使用{%csrf_token%}渲染了一个表单,并在其中使用了ajax代码? If not, Django won't send a new csrf cookie with the response. 如果没有,Django将不会发送带有响应的新csrf cookie。

https://docs.djangoproject.com/en/dev/ref/csrf/#ajax https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. 如果您的视图未呈现包含csrf_token模板标记的模板,则Django可能未设置CSRF令牌cookie。 This is common in cases where forms are dynamically added to the page. 在将表单动态添加到页面的情况下,这很常见。 To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie(). 为了解决这种情况,Django提供了一个视图装饰器来强制设置cookie:sure_csrf_cookie()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM