当我将选择传递给 django 选择小部件时,它不会更新
所以我试图在我的视图中更新选择小部件作为表单的一部分。
我看过很多关于如何做到这一点的东西,我已经遵循了它并几乎做到了。 我下面有一些代码,被称为用选项填充选择,它确实如此,但我认为格式已经过时,因为它传回一个 unicode 字符串,我认为它需要是一个元组。
分配选项
form.fields['size_option'].widget.attrs['choices'] = Product.get_options(product)
生成选项的代码
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
为选择生成的 html 如下。
<select id="id_size_option" name="size_option" choices="(('Small', 'Small')('Medium', 'Medium')('Large', 'Large'))">
所以问题可能是传回的选项集。我也能猜到这么多。我只是不知道出了什么问题。我找不到显示如何在选择内格式化它的文档。
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 followed 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="(('Small', 'Small')('Medium', 'Medium')('Large', 'Large'))">
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是要做什么?选择列表的格式是标准元组:
所以我不明白您想对所有字符串格式做什么。
其次,
choices
不是小部件的attrs
的元素,它是字段和/或小部件本身的属性:在任何情况下,您可能想要使用ModelChoiceField 在这里,然后您可以将
queryset
属性设置为您想要的选项列表。最后,您不使用
Class.method(instance)
调用实例方法,而是使用instance.method()
调用它 - 在您的情况下,product .get_options()
。What is this supposed to be doing? The format for a list of choices is a standard tuple:
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'sattrs
, it is an attribute of the field and/or the widget itself: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 withinstance.method()
- in your case,product.get_options()
.