How to pass a queryset for each different field Admin Inlines

1.9k Views Asked by At

Pretend to have in the Django admin, 4 forms inlines, Each with a pair of fields choices, "Attributes" and "Value Option". We have the first pair, which initialize the field one with a value, for example color and other field you must have a queryset the choices.

Check images please enter image description here

As you can see I need to filter each pair with their default values, if Color should show only white, black and blue.

class ProductAttributeValueForm(forms.ModelForm):
    attribute = forms.ModelChoiceField(label=_('Attribute'),
        widget=forms.Select(attrs={'disabled': 'True'}),
        queryset=ProductAttribute.objects.all(), required=False)

class ProductAttributeValueFormSet(BaseInlineFormSet):

    def __init__(self, *args, **kwargs):
        super(ProductAttributeValueFormSet, self).__init__(*args, **kwargs)
        # This return initial [{'attribute' initial}, {..}, {..}]
        self.initial = [{'attribute': a} for a in obj.category.attributes.all()]
        # Now we need to make a queryset to each field of each form inline
        self.queryset = [{'value_option' .. }, { .. }]

What I do is initialize each attribute with a value, for example, Color and passed a queryset to value_option with their respective values, white, blue and black. I have tried to do this two days ago and I have not accomplished anything, not if the solution is on the forms or in any function of admin

1

There are 1 best solutions below

0
On
class ParametersInlineForm(forms.forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ParametersInlineForm, self).__init__(*args, **kwargs)
        try:
            self.fields['value'].queryset = models.Value.objects.filter(parameter=self.instance.parameter)
        except:
            self.fields['value'].queryset = models.Value.objects.none()


class ParametersInline(admin.StackedInline):
    model = models.Product.parameters.through
    form = ParametersInlineForm