Django AJAX'GET'形式csrf_token无法用于'POST'

时间:2018-10-30 10:32:56

标签: jquery django django-forms django-views

我正在将form装入template中的AJAX。我在模板中加入了{% csrf_token %},但是当我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 %}

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>

1 个答案:

答案 0 :(得分:0)

因此,事实证明我不得不将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})