OrderForm 没有将数据保存到 Django 数据库

OrderForm not saving data to django database

我正在创建一个 Web 应用程序,它允许用户在表单中输入信息,然后将数据保存到 Django 中。一切正常,我可以向模板中的表单添加信息并按提交,但是数据没有保存到数据库中(我在 'Order' table 的管理面板中看不到它。我有if form.is_valid() form.save() 在我的 views.py 文件中应该 POST 数据到我的数据库,但它不是。

有人知道我做错了什么吗?

从models.py

订购模型
class Order(models.Model):
    STATUS = (
            ('Pending', 'Pending'),
            ('Out for delivery', 'Out for delivery'),
            ('Delivered', 'Delivered'),
            )
    # on_delete = If customer is delete, we dont delete child (orders), customer just becomes null without deleting order
    customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL)
    product = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    status = models.CharField(max_length=200, null=True, choices=STATUS)

forms.py

OrderForm class 继承自 CreateOrder views.py

from django.forms import ModelForm
from .models import Order

class OrderForm(ModelForm):
    class Meta:
        model = Order
        fields = '__all__'

createOrder 函数来自 views.py:

def createOrder(request):
    
    form = OrderForm()
    if request.method == 'POST':
        #print('Printing POST:',request.POST)
        form = OrderForm(request.POST)
        #form handles the process of saving to database/
        if form.is_valid():
            form.save
            return redirect('/')
    context = {'form':form}
    return render(request, 'accounts/order_form.html', context)

您正在使用 form.save 调用函数,您忘记了 ():

views.py

def createOrder(request):
    
    form = OrderForm()
    if request.method == 'POST':
        #print('Printing POST:',request.POST)
        form = OrderForm(request.POST)
        #form handles the process of saving to database/
        if form.is_valid():
            form.save()  # Here
            return redirect('/')
    context = {'form':form}
    return render(request, 'accounts/order_form.html', context)