开发者

django select widget doesnt update when i pass the choices into it

so im trying to update in my view a select widget as part of a form.

i'e seen tons of stuff on how to do it, i've fol开发者_如何转开发lowed it and got nearly there. i've got a bit of code below which is called to populate the select with the choices and it does, but i think the formatting is out, as its passing back a unicode string and i think it needs to be a tuple.

assigning the choices

form.fields['size_option'].widget.attrs['choices'] = Product.get_options(product)

the code that generates the choices

def get_options(self):
    optionset = "("
    for option in self.optionset.options.all():
        optionset = optionset + "(\'" + option.name + "\', \'" + option.name + "\')"
    optionset = optionset + ")"
    pdb.set_trace()
    return optionset

the html generated for the select is below.

<select id="id_size_option" name="size_option" choices="((&#39;Small&#39;, &#39;Small&#39;)(&#39;Medium&#39;, &#39;Medium&#39;)(&#39;Large&#39;, &#39;Large&#39;))"> 

so the problem is probably the optionset passed back. i can guess as much. i just don't know whats wrong with it. i cant find documentation that shows how this should be formatted inside the select.


What is this supposed to be doing? The format for a list of choices is a standard tuple:

CHOICES = (
    ('x', 'choice x'),
    ('y', 'choice y'),
)

so I don't understand what you are trying to do with all that string formatting.

Secondly, choices is not an element of the widget's attrs, it is an attribute of the field and/or the widget itself:

form.fields['size_option'].choices = product.get_options()

In any case, you probably want to use a ModelChoiceField here, then you can set the queryset attribute to the list of options you want.

Finally, you don't call an instance method with Class.method(instance), you call it with instance.method() - in your case, product.get_options().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜