Populate a django form with data from database in view

后端 未结 2 1267
轻奢々
轻奢々 2020-12-25 13:21

I have a form in my forms.py that looks like this:

from django import forms

class ItemList(forms.Form):
     item_list = forms.ChoiceField()
2条回答
  •  生来不讨喜
    2020-12-25 14:06

    Take a look at this example in the Django documentation:

    • http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#a-full-example

    Basically, you can use the queryset keyword argument on a Field object, to grab rows from your database:

    class BookForm(forms.Form):
        authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
    

    Update

    If you need a dynamic model choice field, you can hand over your item id in the constructor of the form and adjust the queryset accordingly:

    class ItemForm(forms.Form):
    
        # here we use a dummy `queryset`, because ModelChoiceField
        # requires some queryset
        item_field = forms.ModelChoiceField(queryset=Item.objects.none())
    
        def __init__(self, item_id):
            super(ItemForm, self).__init__()
            self.fields['item_field'].queryset = Item.objects.filter(id=item_id)
    

    P.S. I haven't tested this code and I'm not sure about your exact setup, but I hope the main idea comes across.

    Resources:

    • http://www.mail-archive.com/django-users@googlegroups.com/msg48058.html
    • http://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField

提交回复
热议问题