Populate a django form with data from database in view
Asked Answered
B

2

22

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

from django import forms

class ItemList(forms.Form):
     item_list = forms.ChoiceField()

I need to populate the item_list with some data from the database. When generated in HTML item_list should be something like:

<select title="ItemList">
   <option value="1">Select Item 1</option>
   <option value="2">Select Item 2</option>
</select>

The options values in my select statement will change almost every time since a variable in the query will often change generating new results.

What do I need to put in the view.py and also in my template files to populate the ItemList with values from the database?

Bottrop answered 25/1, 2011 at 2:36 Comment(0)
V
41

Take a look at this example in the Django documentation:

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:

Violative answered 25/1, 2011 at 2:46 Comment(10)
The problem is that all my logic happens in the view.py not in the forms.py. The queryset looks more like this Items.objects.filter(item_id = id). The "id" variable is generated in the view.py.Bottrop
what if you add another parameter to the bookform constructor?Quixote
@The MYYN I think we are close. So how do I plug the item_id value from my view.py?Bottrop
@itgorilla: I don't know your code, but whenever you call something like myform = ItemForm() just pass it the item_id: myform = ItemForm(item_id). Happy hacking.Violative
@The MYYN In case I want pass more variables to the queryset (in the item field above) do I do something like this: def __init__(self, item_id, variable1, varialbe2) ?Bottrop
Almost 100% success. The values on the drop down are correct but the text for all the options looks something like <option value="1">ItemTable Object</option> <option value="2">ItemTable Object</option>. It added the name of the table and the word Object.Bottrop
Meet __unicode__ ;) docs.djangoproject.com/en/dev/ref/models/instances/…Violative
@The MYYN It was very nice to meet Mr. unicode :). That did it! Thank you much!Bottrop
@Violative thanks for the clue, but how if my queryset need an argument. how can I pass my argument into my form with queryset?Tour
Must this be done in a form? Can one use the queryset in a model?Mceachern
B
2

What you need to do is to find out which object do you actually want for e.g. if you want to find out a book named "Upvote-if-u-like!" then your urls.py should like

urlpatterns = [
path('textshare/<str:slug>',views.extract,name="textshare"),]

now when someone will search for mybook.com/textshare/upvote-if-u-like!/

it will take him/her to views.py which would look like

def extract(request,slug):
    context={}

    obj=bookForm.objects.get(title=slug)
    form=bookModelForm(instance=obj)

    context={'form':form}
    return render(request,'bookfound.html',context)

where bookForm is in Models.py and bookModelForm is in forms.py Happy Djangoing:)

Barbaraanne answered 8/10, 2019 at 4:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.