当我用django表单提交时出错

时间:2015-01-16 13:34:20

标签: python django forms

我想发布2个django表单中的数据但是我无法将数据保存到我的数据库中。 为什么?按下提交按钮后,我在价格输入框下方看到“需要”的消息。

我的观点

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')

1 个答案:

答案 0 :(得分:1)

您的“需要此字段”错误不在价格输入框下方,而是在图像选择器上方。您忘记将request.FILES参数传递给ProductImageForm

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

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

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