在我的应用中,我想使用ajax创建和删除课程实例。我已经完成了我的创建功能,它如下:
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()})
这是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);
}
})
})
})
创建课程后,我会在其下面添加一个删除按钮。问题是表单是在没有csrf标记的情况下创建的,但我不知道如何使用jquery添加表单,因为csrf标记是python。关于如何解决这个问题的任何想法?
答案 0 :(得分:0)
根据关于CSRF Protection的Django文档,您有2个选项:
通过以下方式在Javascript中设置CSRF令牌:
{% csrf_token %}
<script type="text/javascript">
// using jQuery
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
</script>
从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);
}
}
});