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

后端 未结 2 1935
自闭症患者
自闭症患者 2021-01-08 00:41

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,

2条回答
  •  佛祖请我去吃肉
    2021-01-08 00:56

    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.

提交回复
热议问题