为简单起见,这是我正在处理的问题的简短版本。假设您有两个模型,分别是Product和ProductPricing,其中Product具有许多ProductPricing实例,并且一个产品的定价仅与一个产品有关(一对多关系)。模型的清洁方法:
models.py:
class ProductPricing(models.Model):
product = models.ForeignKey(Product, related_name = 'prices', verbose_name = 'Price', blank = True, null = True)
customer = models.ForeignKey(Customer, related_name = 'customer_pricings', blank = True, null = True)
...
def clean(self):
if not self.product and not self.customer:
raise ValidationError(_('Pricing requires either a product or a customer. None is provided') )
forms.py:
class ProductPricingAddonForm(ModelForm):
class Meta:
model = ProductPricing
fields = ['UOM', 'cost_per_UOM', 'product']
现在,在我的UpdateView中,我正在执行以下操作:
class UpdateProductView(View):
template_name = 'product.html'
product_form = ProductForm
pricing_form = ProductPricingAddonForm
def get(self, request, *args, **kwargs):
product_id = kwargs.get('pk', None)
product = Product.objects.get(id = product_id)
product_form = self.product_form()
pricing_form = self.pricing_form()
c = {}
c['product_form'] = product_form
c['pricing_form'] = pricing_form
return render(request, self.template_name, c)
def post(self, request, *args, **kwargs):
''' To update both the models in one go'''
product_id = kwargs.get('pk', None)
product = Product.objects.get(id = product_id)
product_pricing = ProductPricing.objects.filter(product = product)
product_form = self.product_form(request.POST if any(request.POST) else None, request.FILES or None, instance = product)
if product_form.is_valid():
product_form.save()
product_form_validity_flag = True
updated_product = Product.objects.get(id = product_id)
else:
product_form_errors = product_form.errors
...
# if no existing pricing specified for the product:
pricing_form = self.pricing_form(request.POST if any(request.POST) else None, request.FILES or None)
# Since a productpricing instance is required to have product or customer, the updated_product should somehow be attached to the form:
pricing_form['product'] = updated_product # <-- Error here
if pricing_form.is_valid():
pricing_form.save()
pricing_form_validity_flag
else:
pricing_form_errors = pricing_form.errors
if product_form_validity_flag and pricing_form_validity_flag:
return reverse(...)
else:
c = {'product_form': product_form,
'pricing_form': pricing_form }
return render(request, self.template_name, c)
问题是提交表单时,出现错误消息“ ProductPricingAddonForm”对象不支持项目分配。请注意,如果我不以某种方式将产品提供给productpricing表单,则ProductPricing模型的clean方法中定义的验证错误将引发我。
所以,我的问题是如何在相同的post方法中将父实例(产品)附加到子实例(产品定价)(即不在其他页面中创建产品定价)?