我试图通过使用ajax请求将新对象添加到我的数据库中:
这是我的JS:
$('#add-book').click(function(e) {
e.preventDefault();
var $modal = $('.modal-body');
var $form = $('#book-form');
var data = {};
data['name'] = $modal.find('input[name=name]').val();
data['author'] = $modal.find('input[name=author]').val();
data['major'] = $modal.find('input[name=major]').val();
data['course'] = $modal.find('input[name=class]').val();
data['price'] = $modal.find('input[name=price]').val();
data['university'] = $body.data('university');
$.ajax({
url: '/ws/add_book/',
type: 'POST',
data: data,
});
});
和我的views.py:
的一部分@csrf_exempt
def add_book(request):
university = request.POST.get('university')
university_object = University.objects.get(name=university)
name = request.POST.get('name')
author = request.POST.get('author')
major_name = request.POST.get('major')
major = Major.objects.get(name=major_name, university=university_object)
course = request.POST.get('course')
price = Decimal(request.POST.get('price'))
post_date = datetime.now()
d = dict(name=name, author=author, major=major, course=course, price=price,
user=request.user, post_date=post_date)
textbook = TextBook(**d)
textbook.save()
return HttpResponse('')
我一直收到500内部服务器错误,回复“大学匹配查询不存在”。这很奇怪,因为我知道我的数据库中有一个匹配名称的对象。
任何人都知道我的问题是什么?