【问题标题】:Django AJAX 'GET' form csrf_token not working for 'POST'Django AJAX 'GET' 表单 csrf_token 不适用于'POST'
【发布时间】:2018-10-30 10:32:55
【问题描述】:

我正在用AJAXtemplate 中加载form。我在模板中包含了{% csrf_token %},但是当我POSTform 时,我得到csrf error 屏幕。我尝试了一些我见过的不同的东西,但都没有奏效。

原图:

def customer_profile(request, pk):
    name = get_object_or_404(CEName, id=pk)
    return render(
        request,
        'customer/customer_profile.html',
        {'profile_name': name}
    )

原始模板:

{% block content %}
  {% include 'ce_profiles/name_header.html' %}
  <div id="name" class="container d-flex justify-content-between pt-1">
    {% include 'ce_profiles/profile_name.html' %}
    <button id="update_button" action="{% url 'ce_profiles:profile-update-name' profile_name.id %}" class="bold btn btn-main btn-sm button-main">UPDATE</button>
  </div>
  <div id="div_NameForm" class="container">
  </div>
{% endblock %}

{% block script %}
  <script src="{% static 'ce_profiles/ce_profiles.js' %}"></script>

{% endblock %}

script.js

$(document).ready(function() {
  $("#NameForm").submit(function(event) {
    event.preventDefault();
    $.ajax({
      url: $(this).attr('action'),
      type: $(this).attr('method'),
      data: $(this).serialize(),
      dataType: 'json',
      success: function(data) {
          $('#profile_name').html(data.profile_name);
      }
    });
  });
});
let updateButton
let toggleNameForm = function(e) {
  e.stopPropagation();
  let btn = this;
  if (btn.innerHTML === "UPDATE") {
    $.ajax({
      url: $(this).attr('action'),
      type: 'GET',
      dataType: 'json',
      success: function(data) {
          $('#div_NameForm').html(data.NameForm);
      }
    });
    btn.innerHTML = "CANCEL";
    btn.classList.replace("button-main", "button-secondary");
  } else {
    $('#div_NameForm').html('<div id="div_NameForm" class="container"></div>');
    btn.innerHTML = "UPDATE";
    btn.classList.replace("button-secondary", "button-main");
  }
};


document.addEventListener('DOMContentLoaded', function () {
  updateButton = document.getElementById('update_button');
  updateButton.addEventListener('click', toggleNameForm);
});

表单视图和模板:

def profile_update_name(request, pk):
    name = get_object_or_404(CEName, id=pk)
    if request.POST:
        name_form = NameForm(data=request.POST, instance=name)
        if name_form.has_changed() == False:
            name_form.add_error(None, _('No changes made.'))
        if name_form.is_valid():
            name_form.save()
            updated_name = get_object_or_404(CEName, id=name.id)
            profile_name_json = render_to_string(
                'ce_profiles/profile_name.html',
                {'profile_name': updated_name,}
            )
            return JsonResponse({'profile_name': profile_name_json})
        else:
          return JsonResponse({'error': name_form.errors})
    else:
        name_form = NameForm(instance=name)
        get_NameForm_json = render_to_string(
            'ce_profiles/update_NameForm.html',
            {'NameForm': name_form, 'profile_name': name}
        )
        return JsonResponse({'NameForm': get_NameForm_json})

<hr size="3px">
<form id="NameForm" method="POST" action="{% url 'ce_profiles:profile-update-name' profile_name.id %}">
  {% csrf_token %}
  {{ NameForm.as_p }}
  <div id="NameForm_errors"></div>
  <br>
  <button id="save_changes" type="submit" class="btn btn-main button-main btn-block">Save Changes</button>
</form>

【问题讨论】:

  • 当您发布表单时,您能看到csrfmiddlewaretoken 参数正在浏览器的网络选项卡中发送吗?
  • 是的。 403 POST /ce_profiles/profile-update-name/1/Cookie csrftoken=rpJo...
  • 我的终端说csrf missing or incorrect@WillKeeling

标签: jquery django django-forms django-views


【解决方案1】:

结果我不得不将request 添加到render_to_string,因为我的AJAX 调用没有呈现{% csrf_token %}。我的视图现在看起来像:

else:
    name_form = NameForm(instance=name)
    get_NameForm_json = render_to_string(
        'ce_profiles/update_NameForm.html',
        {'NameForm': name_form, 'profile_name': name},
        # added 'request'
        request=request
    )
    return JsonResponse({'NameForm': get_NameForm_json})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2015-06-03
    • 2018-03-06
    • 1970-01-01
    • 2017-12-24
    • 2020-05-30
    相关资源
    最近更新 更多