我有一个Django项目,我目前正在工作,我希望能够将产品添加到数据库中。我有几个字段,用户在其中输入产品的详细信息,然后将其发送到create函数,并将其保存到数据库中。不幸的是,这并没有发生。这是我第一次使用Django,所以我不确定这里出了什么问题。以下是我目前掌握的代码:
我的索引.html页码:23/46
Create product here
{% csrf_token %}
Name:
description:
price:
$(document).on('submit', '#new_user_form', function(e)){
e.preventDefault()
$.ajax({
type: 'POST',
url:'/user/create',
data:{
name:$('#name').val(),
description:$('#description').val(),
price:$('#price').val(),
}
success.function(){
console.log('created')
}
})
}
这是我的网址.py代码:
^{pr2}$
我的视图.py代码:from django.shortcuts import render
from testapp.models import User
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
def index(request):
return render(request, 'index.html')
@csrf_exempt
def create_product(request):
if request.method == 'POST':
name = request.POST['name']
description = request.POST['description']
price = request.POST['price']
User.objects.create(
name = name,
description = description,
price = price
)
return HttpResponse('')
以及模型.py代码:from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length = 32)
desscription = models.TextField()
price = models.CharField(max_length = 128)
问题是POST请求在运行时被发送,但是数据没有保存到数据库中,我不知道为什么。我已经遵循了一些教程和文档来达到这个阶段,但是我不知道是什么东西在这里不能正常工作。有人能看看我吗?在