有模特:
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
variation_1 = models.BooleanField(default=True)
variation_2 = models.BooleanField(default=True)
variation_3 = models.BooleanField(default=True)
class Order(models.Model):
buyer = models.ForeignKey(User, related_name='buyer')
product = models.ForeignKey(Product)
variations_select = models.CharField(max_length=50, choices=VARIATIONS)
在forms.py 中
我需要创建一个干净的函数来检查 class OrderForm(forms.ModelForm):
variations_select = forms.ChoiceField(choices=VARIATIONS)
class Meta:
model = Order
fields = [
'variations_select'
]
variation_1
中variation_2
或variation_3
或Product
是否可用。{1}}。为此,需求请求Product.id
到def clean_variations_select(self):
如何执行此操作?def clean_variations_select(self):
product = Product.object.get(id = product.id)
variations_select = self.cleaned_data.get("variations_select")
if variations_select == "Variation_1" and product.variation_1 == False:
raise forms.ValidationError("variation_1 was sold already")
else:
return variations_select
product = Product.object.get(id = product.id)
- 不工作原因订单尚未创建到数据库(但在渲染视图链接到新订单创建我有那个../product.id/new_order)。
答案 0 :(得分:1)
您需要为您的班级定义__init__
方法,该方法应接受您的产品ID作为参数。
def __init__(self,*args,**kwargs):
self.product_id = kwargs.pop('product_id')
super(OrderForm,self).__init__(*args,**kwargs)
初始化表单时,会将product_id
作为关键字参数传递。
OrderForm(request.POST, product_id=product_id)
使用简洁方法,您可以使用self.product_id
获取所需的Product
对象。
def clean_variations_select(self):
product = Product.object.get(id=self.product_id)
variations_select = self.cleaned_data.get("variations_select")
if variations_select == "Variation_1" and product.variation_1 == False:
raise forms.ValidationError("variation_1 was sold already")
else:
return variations_select