3

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.

Arpit Solanki
  • 9,567
  • 3
  • 41
  • 57
  • define the `not working`. Is it throwing any error? Are your fields not showing correctly? – Arpit Solanki Aug 20 '17 at 19:02
  • I'd guess that it's not expecting `partType` keyword when calling parent class `__init__`. If so, you should move this line `partType = kwargs.pop('partType')` to the top of your `__init__` method – mateuszb Aug 20 '17 at 21:36
  • I moved the pop to earlier and there were no errors produced but the list of parts is not a list that is limited by the partType value on the line (which is what I need. – appdev epiccycles Aug 22 '17 at 15:20

1 Answers1

6

you can use 'self.instance.key_name' to the access the value.

Mukul Kumar
  • 76
  • 1
  • 2