model 1
class Products(models.Model):
product_category = models.ForeignKey(ProductCategory)
product_sub_category = models.ForeignKey(ProductCategory)
product_name = models.CharField(max_length = 200)
is_active = models.BooleanField(default = True)
and so on...
model 2
class ProductImages(models.Model):
product = models.ForeignKey( Products )
product_image = models.FileField(_('Attachment'), upload_to='attachments')
is_active = models.BooleanField(default = True)
CreateView
class ProductCreate(CreateView):
model = Products
template_name = "products/product_add.html"
fields = ['product_category', 'product_sub_category', 'product_name', 'size', 'color', 'price', 'price_info', 'description_1', 'description_2', 'about_product', 'features', 'specification']
success_url = "products/product-list"
def form_valid(self, form):
product_form = form.save(commit = False)
# **expecting product_form.id to be non None**
if 'product_images' in self.request.FILES:
for img in self.request.FILES.getlist('product_images'):
ProductImages(product = product_form, product_image = img).save()
super(ProductCreate, self).post(request, *args, **kwargs)
问题陈述:
form.save(commit = False)返回Product实例但产品ID为None。期望对象id是非法的,因为对象尚未保存到db?
答案 0 :(得分:0)
是。 id由数据库分配,并且由于commut=False
明确表示“不发送到db”,因此它不具有id。