如何在Django表单中编辑选择选项值?

时间:2015-11-16 20:15:43

标签: python django

我想在django表单中编辑选择选项值。 现在,select中选项的值是相关的variant_id。

models.py

class ReceiptDetail(models.Model):
    variant = models.ForeignKey('ProductVariant')

forms.py

class ReceiptDetailForm(forms.ModelForm)    
    class Meta:
        model = ReceiptDetail
        fields = ['product_id', 'variant', 'size', 'quantity', 'price']

从'variant'中选择产生的html:

<option value="" selected="selected">---------</option>
<option value="98">Charm I (Charm I)</option>
<option value="97">Small potion V (Small potion V)</option>
<option value="90">Big potion V (Big potion V)</option>
<option value="100">Charm III (Charm III)</option>
<option value="93">Small potion I (Small potion I)</option>
<option value="94">Small potion II (Small potion II)</option>
<option value="81">Colorfully (Colorfully)</option>

请注意,每个选项的值都是VARIANT id。我想将该值更改为PRODUCT id(与变体相关)。

我猜小部件是答案,但我不知道如何访问select对象中的选项属性。这是我尝试过的:

widgets.py:

class VariantIDWidget(forms.widgets.Select):

    def __init__(self, *args, **kwargs):
        super(VariantIDWidget, self).__init__(*args, **kwargs)

    def render(self, name, value, attrs=None):
        out = super(VariantIDWidget, self).render(name, value,
            attrs={'value': 'test'})
        return out

这将更改&lt; \ select&gt;的值,而不是其相关的&lt; \ options&gt ;.

1 个答案:

答案 0 :(得分:2)

我认为您应该排除表单中定义的variant中的fields,并使用__init__方法执行某些操作:

class ReceiptDetailForm(forms.ModelForm)    
    class Meta:
        model = ReceiptDetail
        fields = ['product_id', 'size', 'quantity', 'price']

    def __init__(self, *args, **kwargs):
        super(ReceiptDetailForm, self).__init__(*args, **kwargs)
        # this is pseudo code but you should get all variants
        # then get the product related to each variant
        variants = Variant.objects.all()
        products = [(i.product.id, i.product.name) for i in variants]
        self.fields['product'] = forms.ChoiceField(choices=products)

这是一种常见的技巧,请参阅其他一些SO questions