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,
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.
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.