简体   繁体   English

Django AJAX请求:创建和删除课程。 删除课程无效

[英]Django AJAX requests: create and delete a course. deleting a course not working

In my app, I want to create and delete instances of Course using ajax. 在我的应用程序中,我想使用ajax创建和删除Course实例。 I have finished my create functionality, and it is as follows: 我已经完成创建功能,如下所示:

urls.py urls.py

app_name = 'courses'

urlpatterns = [
    path('index/', views.index, name='index'),
    path('create/', views.create, name='create'),
    path('delete/<int:course_id>/', views.delete, name='delete'),

]

views.py views.py

from django.shortcuts import render, redirect
from courses.models import Course
from django.http import JsonResponse
from django.forms.models import model_to_dict
# Create your views here.

def index(request):
    context = {
        'courses':Course.objects.all(),
    }
    return render(request, 'courses/index.html', context)

def create(request):
    if request.method == 'POST':
        course = Course.objects.create(name=request.POST['name'], description=request.POST['description'])
        # return redirect('courses:index')
        # course is a queryset, we need to change it to a dictionary
        return JsonResponse(model_to_dict(course))
    else:
        return render(request, 'courses/index.html')

def delete(request, course_id):
    course = Course.objects.get(pk=course_id)
    if request.method == 'POST':
        course.delete()
        courses = Course.objects.all()

        return JsonResponse((courses))

        # return JsonResponse(model_to_dict(course))
    else:
        return render(request, 'courses/index.html', {'courses':Course.objects.all()})

here is the jquery for it: 这是它的jQuery:

$(document).ready(function(){

  $('.course_form').submit(function(event){
    console.log(event);
    event.preventDefault();
    $.ajax({
                url: '/courses/create/',

      method: 'post',
      data: $(this).serialize(),
      success: function(response){
        console.log(response);
        $('.courses').append(`<p>Name: ${response.name},
                              Description: ${response.description}</p>
                              <form class="delete_form" action="/courses/delete/${response.id}/" method="post">

                                <input type="submit" value="delete">
                              </form>
                              `)

        $('.course_form')[0].reset();

      }
    });

  })
  $('delete_form').submit(function(event){
    console.log(event);
    event.preventDefault();
    $.ajax({
      url: '/courses/delete/',
      method: 'post',
      success: function(response){
        console.log(response);
      }
    })
  })
})

once I create a course, I append a delete button under it. 创建课程后,我将在课程下方添加一个删除按钮。 the problem is that the forms are being created without a csrf token, but i dont know how to add one using jquery, given that the csrf token is python. 问题是正在创建的表单没有csrf令牌,但鉴于csrf令牌是python,我不知道如何使用jquery添加表单。 any ideas on how to solve this issue? 关于如何解决此问题的任何想法?

You have 2 options based on the Django docs about CSRF Protection : 基于Django文档,您有2个关于CSRF保护的选项

  1. Set the CSRF token in Javascript via: 通过以下方式在Javascript中设置CSRF令牌:

     {% csrf_token %} <script type="text/javascript"> // using jQuery var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); </script> 
  2. Get it from the csrftoken cookie and set it for all AJAX request: csrftoken cookie中获取它,并为所有AJAX请求设置它:

     function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM