如何在表单清理数据功能中请求object.id

时间:2016-12-10 21:23:55

标签: django forms object django-forms request

有模特:

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_1variation_2variation_3Product是否可用。{1}}。为此,需求请求Product.iddef 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)。

1 个答案:

答案 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