Django ModelForm instance with custom queryset for a specific field

Deniz Dogan picture Deniz Dogan · Nov 30, 2009 · Viewed 37.4k times · Source

I have a model not unlike the following:

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

All users may work at a number of factories and therefore their user profiles all have a ManyToManyField to Factory.

Now I want to construct a ModelForm for Bike but I want the made_at list to consist of only factories at which the current user works. The idea is that users should be able to add bikes that they've assembled and enter which of the factories the bike was made at.

How do I do that?

Answer

Dave picture Dave · Nov 30, 2009

try something like this in the view

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

modify the Factory queryset so that it identifies the factory which the user works at.