Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I construct a Django form with model objects in a Select widget?

Tags:

django

Let's say I'm using the Django Site model:

class Site(models.Model):
    name = models.CharField(max_length=50)

My Site values are (key, value):

1. Stackoverflow
2. Serverfault
3. Superuser

I want to construct a form with an html select widget with the above values:

<select>
    <option value="1">Stackoverflow</option>
    <option value="2">Serverfault</option>
    <option value="3">Superuser</option>
</select>

I'm thinking of starting with the following code but it's incomplete:

class SiteForm(forms.Form):
    site = forms.IntegerField(widget=forms.Select())

Any ideas how I can achieve that with Django form?

EDIT

Different pages will present different site values. A dev page will show development sites while a cooking page will show recipe sites. I basically want to dynamically populate the widget choices based on the view. I believe I can achieve that at the moment by manually generating the html in the template.

like image 407
Thierry Lam Avatar asked Mar 31 '10 19:03

Thierry Lam


2 Answers

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.

like image 61
Hank Gay Avatar answered Oct 24 '22 05:10

Hank Gay


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.

like image 36
T. Stone Avatar answered Oct 24 '22 07:10

T. Stone