使用Ajax将表单数据发送到Django视图

时间:2018-03-30 23:20:24

标签: javascript python django

我想使用模板中的选定值在几个月内过滤数据,但仍然会收到403(禁止)错误。 这是我的文件:

Models.py

class FuelOperation(models.Model):
    date = models.DateField(default=datetime.date.today)
    liter = models.IntegerField()

Template.html

<form id="month-form" method="post">
{% csrf_token %}
<select id="month-select" class="selectpicker">
<option value="03" name="March">3</option>
<option value="04" name="April">4</option>
</select>
</form>

的Javascript

  $("#month-select").on("change", function(){
  var selectedValue = $(this).text();

  $.ajax({
    url : "{% url 'index' %}",
    type : "POST",
    data : {"value" : selectedValue},
    dataType : "json",
    success : function(){

    }
  });
});

views.py

def index(request):
    if request.method == 'POST':
        key = request.POST.get('value')
        operations = FuelOperation.objects.filter(date__month=key)
        context = {'operations': operations}
        return HttpResponse(simplejson.dumps({"success": "true"}, mimetype="application/json"))

    return render(request, 'fuel/index.html', context)

urls.py

path('', views.index, name='index'),

1 个答案:

答案 0 :(得分:0)

对于使用Django的jQuery AJAX,您需要添加一些东西来处理CSRF。在您的javascript文件中,添加以下内容:

  /*
   * CSRF Token Using jQuery 
   */
   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;
  }
  var csrftoken = getCookie('csrftoken');
  function csrfSafeMethod(method) {
      // these HTTP methods do not require CSRF protection
      return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }
  $.ajaxSetup({
    beforeSend: function(xhr, settings) {
      if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      }
    }
  });