简体   繁体   中英

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. I have finished my create functionality, and it is as follows:

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

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:

$(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. any ideas on how to solve this issue?

You have 2 options based on the Django docs about CSRF Protection :

  1. Set the CSRF token in Javascript via:

     {% 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:

     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); } } }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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