Django,CSRF令牌出错!我在哪里看?

时间:2019-03-28 06:02:26

标签: django csrf django-csrf django-middleware

我在查看日志文件时,发现了许多与CSRF相关的错误日志

我在下面收到警告日志

Forbidden (CSRF token missing or incorrect.): /my/site/uri

并在下面的错误日志之后

Internal Server Error: /my/site/uri
Traceback (most recent call last):
File "/data/kukkart_env/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 140, in get_response
response = middleware_method(request, callback, callback_args, callback_kwargs)
File "/data/kukkart_env/local/lib/python2.7/site-packages/django/middleware/csrf.py", line 216, in process_view
return self._reject(request, REASON_BAD_TOKEN)
File "/data/kukkart_env/local/lib/python2.7/site-packages/django/middleware/csrf.py", line 106, in _reject
return _get_failure_view()(request, reason=reason)
TypeError: server_error() got an unexpected keyword argument 'reason'

这里有一个供购物车提交的表格。 表单中有一个CSRF_TOKEN

{% block cart %}
   <form class="form-horizontal" method="post" action="/my/site/uri/">
     {% csrf_token %}
      <div class="modal" id="cartShowAllModal">
        <div class="modal_wrap">
          <div class="modal_content">
            <h5 class="title">Cart</h5>
            <div class="content-box">
              <div class="modal_cart_wrap">
                <div class="inner">
                  <ul class="cart_list">
                  {{ cart_form.product_formset.management_form }}
                  {% if cart_form.total_count != 0 and cart_form.total_count %}
                    {% for product_form in cart_form.product_formset %}
                  </ul>
                  <div id="cart_message_empty" class="cart_list empty" style="display: none;">
                  {% else %}
                  <div id="cart_message_empty" class="cart_list empty" style="display: block;">
                  {% endif %}
                    <p class="txt"><span class="blind">Empty Cart</span></p>
                  </div>
                </div>
              </div>
            </div>

            <div class="cart_func">
              {% if cart_form.total_count != 0 %}
              <button id="cart_close" type="button" class="btn cancel"><span>Continue Shopping</span></button>
              <button id="cart_message_checkout" type="submit" class="btn checkout"><span>Checkout</span></button>
              {% endif %}
            </div>
            <script>
              $('#cart_close').on('click', function () {
                  closeModal();
              })
            </script>

            <a href="#" class="close"><span class="blind">Close Popup</span></a>
          </div>
        </div>
      </div>
      </form>
    {% endblock %}

views.py是这个

我不知道问题是什么。

class CartSubmitView(CheckoutClearSessionMixin, View):
    def post(self, request, *args, **kwargs):
        if 'cart_product_pks' not in self.request.session:
            return HttpResponseRedirect('/')

        if len(self.request.session['cart_product_pks']) == 0:
            return HttpResponseRedirect('/')

        if self.request.user.is_authenticated() and self.request.user.is_non_registered:
            from account import views as account_views
            account_views.logout(request)
            return HttpResponseRedirect('/account/login/?next=/order/checkout/')

        for cart_product_pk in self.request.session['cart_product_pks']:
            for key, value in self.request.POST.items():
                try:
                    if int(value) == int(cart_product_pk):
                        quantity = int(self.request.POST[key.replace('id', 'quantity')])
                        order_product = models.OrderProduct.objects.get(pk=cart_product_pk)
                        order_product.quantity = quantity
                        order_product.save()
                except:
                    continue

        self.request.session['cart_checkout'] = True
        self.request.session['order_product_pks'] = self.request.session['cart_product_pks']

        return HttpResponseRedirect('/order/checkout/')

这里没有太多与csrf令牌相关的源代码

是什么导致此错误?

1 个答案:

答案 0 :(得分:0)

这意味着您提交的表单缺少用于防止恶意攻击的csrf_token

要在表单中集成csrf_token,应添加{% csrf_token %}。示例:

<form>
{% csrf_token %}
<input type="text" />
</form>

要集成到AJAX请求中,可以使用{{ csrf_token }}变量。示例:

var data = {
    csrfmiddlewaretoken: "{{csrf_token}}",
    ...
};

$.ajax({
    type: 'POST',
    url: 'url/to/ajax/',
    data: data,
    dataType: 'json',
    ...
});