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

后端 未结 2 1910
自闭症患者
自闭症患者 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题