[Fixed]-How do I construct a Django form with model objects in a Select widget?

18👍

I think you’re looking for ModelChoiceField.

UPDATE: Especially note the queryset argument. In the view that is backing the page, you can change the QuerySet you provide based on whatever criteria you care about.

15👍

I haven’t tested this, but I’m thinking something along the lines of…

site = forms.IntegerField(
    widget=forms.Select(
        choices=Site.objects.all().values_list('id', 'name')
        )
     )

Edit —

I just tried this out and it does generate the choices correctly. The choices argument is expecting a list of 2-tuples like this…

(
   (1, 'stackoverflow'),
   (2, 'superuser'),
   (value, name),
)

The .values_list will return that exact format provided you have the ID and the name/title/whatever as so: .values_list('id', 'name'). When the form is saved, the value of .site will be the id/pk of the selected site.

Leave a comment