Time
Time

Reputation: 57

how to pull form values in django from a database?

am currently working on a project and i designed my form using django form class, the issue is that i want a ChoiceField from the form class to pull the value of the choices from my database. i wrote a function like this:

from django import forms
from django.forms.widgets import Select
from django.forms.fields import ChoiceField
import datetime
from mystore.store.models import categories

def header_search():
cat_values = ""
cats_list = categories.objects.all().order_by('category', 'values')
for cat in cats_list:
cat_values += "('%s', '%s'),"%(cat.values, cat.values)
return cat_values

mylist = header_search()

CATEGORY_CHOICES = (mylist)


class headersearch(forms.Form):
kywords = forms.CharField(max_length = 100)

category = forms.ChoiceField(widget=forms.Select, choices=CATEGORY_CHOICES)

this function actually worked when i ran it using manage.py shell, but each time i try it over the server i my error page:

TemplateSyntaxError at / Caught ValueError while rendering: need more than 1 value to unpack.

Upvotes: 0

Views: 1043

Answers (2)

Why are you using strings to represent a list? That's rather bizzarre when you could be using python.

Your list(my_list) should just be returning a list of X characters. list('abcd') results in ['a', 'b', 'c', 'd'].

choices expects a list of tuples. Just modify your code to return a list of tuples instead of a string representation of a list of tuples.

def header_search():
    cat_values = []
    cats_list = categories.objects.all().order_by('category', 'values')
    for cat in cats_list:
        cat_values.append((cat.values, cat.values))
    return cat_values

PS: with this method, your choices will only be populated once (per django loading). If you want dynamic values a more appropriate place for this is in the form init function.

class MyForm(..):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['category'].choices = my_choices

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599620

ModelChoiceField.

Upvotes: 1

Related Questions