0

I have a form like so:

class ThingSelectionForm(forms.Form):
    things = forms.ModelChoiceField(
        queryset=Product.objects.filter(product=my_product),
        widget=forms.RadioSelect,
        empty_label=None,
    )

My question is - how do I pass in the my_product variable when a page loads? Should I create a custom __init__ method?

Any help much appreciated.

Darwin Tech
  • 18,449
  • 38
  • 112
  • 187

2 Answers2

3

Yes you can override the init

    class ThingSelectionForm(forms.Form):
        things = forms.ModelChoiceField(
            widget=forms.RadioSelect,
            empty_label=None,
        )
       def __init__(self, *args, **kwargs):
              my_prod = kwargs.pop('my_prod), None
              super(...)
              self.fields['things'].queryset = Product.objects.filter(product=my_prod),

#view

form = ThingSelectionForm(my_prod = my_prod)
Raunak Agarwal
  • 7,117
  • 6
  • 38
  • 62
1

I just was working on something like this today. I found this to be helpful. It's the answer from Dave

models.py

class Bike(models.Model):
    made_at = models.ForeignKey(Factory)
    added_on = models.DateField(auto_add_now=True)

view.py

form  = BikeForm()
form.fields["made_at"].queryset = Factory.objects.filter(user__factory)

I did mine with a filter(foo=bar) type query.

Then in the forms.py

made_at = forms.ModelChoiceField(queryset=Factory.objects.all())
Community
  • 1
  • 1
bDreadz
  • 123
  • 1
  • 6