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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With