即使在传递CSRF_TOKEN之后,在Django Ajax中也出现403禁止错误

时间:2020-10-04 16:53:20

标签: python django ajax

我正在使用模式弹出框在Django中创建Modal实例。这是模态主体内的形式:

<form
  action="{% url 'projects:techs_create' %}"
  method="post"
  id="tech-form"
>
  {% csrf_token %}
  <input type="text" name="name" id="tech-name" />
  <input type="submit" value="Save" class="button button-main" />
</form>

这是我使用的Ajax请求

  $(document).on("submit", "#tech-form", function (e) {
    e.preventDefault();
    $.ajax({
      type: "POST",
      url: $(this).attr("action"),
      dataType: "json",
      contentType: "application/json",
      // data: $(this).serialize(),
      data: {
        name: $("#tech-name").val(),
        csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(),
      },
      success: function (response) {
        console.log('done')
      },
      error: function (xhr, status, error) {
        console.log(error.msg);
      },
    });
  });

我收到此错误:

POST http://localhost:8000/techs/new/ 403 (Forbidden)

我在SO中看到了一些类似的问题,大多数答案都在谈论丢失的csrf令牌。现在,我将其添加为请求数据。我仍然遇到错误。我在这里做什么错了?

这是我用来处理请求的视图:

@login_required
def techs_create_view(request):
    if not request.user.is_superuser:
        raise PermissionDenied

if request.method == 'POST':
    form = ProjectTechnologieForm(request.POST)
    if form.is_valid():
        name = form.cleaned_data.get('name')
        form.save()
        messages.success(request, f'{name} created successfully.')
        return HttpResponseRedirect('projects:statistics')

    form = ProjectTechnologieForm()

    context = {
       'tech_form': form
    }

    if request.is_ajax():
        html = render_to_string('projects/statistics.html',
                            context, request=request)
        return JsonResponse({'form': html})

谢谢

0 个答案:

没有答案