简体   繁体   中英

how do I access a django form value in the __init__ method for a query

I have a model that includes a foreign key:

class Part(models.Model):
    partType = models.ForeignKey(PartType, on_delete=models.CASCADE)
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    part_name = models.CharField(max_length=60)

class QuotePart(models.Model):
    quote = models.ForeignKey(Quote, on_delete=models.CASCADE)
    line = models.PositiveSmallIntegerField(default=1)
    partType = models.ForeignKey(PartType, on_delete=models.CASCADE)
    # part can be None if the part has not been selected
    part = models.ForeignKey(Part, on_delete=models.CASCADE,blank=True,null=True)

I have a form that allows parts to be added to a quote and want to want to limit the choices on the form to just the Parts that are the right PartType but my code is not working:

    class QuoteBikePartForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(QuoteBikePartForm, self).__init__(*args, **kwargs)
        self.fields['partType'].widget.attrs['disabled'] = True
        self.fields['frame_part'].widget.attrs['disabled'] = True
        partType = kwargs.pop('partType')
        self.fields['part'].queryset = Part.objects.filter(partType=partType.pk)

    class Meta:
        model = QuotePart
        fields = ['quote','line','partType','frame_part', 'part', 'quantity','cost_price', 'sell_price']

QuoteBikePartFormSet = inlineformset_factory(Quote, QuotePart, form=QuoteBikePartForm)

I have tried a number of different things and so far no luck.

您可以使用'self.instance.key_name'来访问该值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM