首页 > 解决方案 > Django AJAX 'GET' 表单 csrf_token 不适用于 'POST'

问题描述

我正在加载form一个templatewith AJAX。我已经{% csrf_token %}在模板中包含了 a ,但是当我POST使用时form,我得到了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 %}

脚本.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>

标签: jquerydjangodjango-formsdjango-views

解决方案


所以事实证明我必须将 . 添加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})

推荐阅读