当我使用 django 表单提交时出现错误

I got error when I submit with django form

我想 post 来自 2 个 django 表单的数据,但我无法将数据保存到我的数据库中。 为什么?按下提交按钮后,我在价格输入框下方看到消息 "it is required"。

我的观点

def addproduct(request):

   user = request.user
   product_form = ProductForm(request.POST or None)
   product_image_form = ProductImageForm(request.POST or None)

   if product_form.is_valid() and product_image_form.is_valid():
      product = product_form.save(commit=False)
      product.user = request.user
      product.slug = slugify(product_form.cleaned_data['title'])
      product.featured = False
      product.active = False
      product.save()
      product_image = product_image_form.save(commit=False)
      product_image.featured = False
      product_image.save()
      return HttpResponseRedirect('/products/%s'%(product.slug))

我的模型

class Product(models.Model):
   user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)
   title = models.CharField(max_length=120)
   description = models.TextField(null=True, blank=True)
   price = models.DecimalField(decimal_places=0, max_digits=100, default=0)
   slug = models.SlugField(unique=True)

class ProductImage(models.Model):
   product = models.ForeignKey(Product)
   image = models.ImageField(upload_to='products/images/')
   featured = models.BooleanField(default=False)

我的表格

from django import forms
from .models import Product, ProductImage

class ProductForm(forms.ModelForm):
   class Meta:
       model = Product
       fields = ('title', 'description', 'price')

class ProductImageForm(forms.ModelForm):
   class Meta:
       model = ProductImage
       fields = ('image', 'featured')

您收到 "This field is required" 错误,错误不是在价格输入框下方而是在图像选择器上方。您忘记将 request.FILES 参数传递给 ProductImageForm:

product_image_form = ProductImageForm(request.POST or None,
                                      request.FILES or None)

并且不要忘记在 <form> 标签中指定 enctype 属性:

<form method="post" enctype="multipart/form-data">