gpt4 book ai didi

Django CheckboxSelectMultiple 从 ModelForm 覆盖 'choices'

转载 作者:行者123 更新时间:2023-12-01 15:02:15 25 4
gpt4 key购买 nike

我希望能够在我的 django 表单中提取不同的信息:

这是我的表格:

<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

class InstanceForm(ModelForm):
class Meta:
model = models.BaseAsset
widgets = {
'labels': LabelIconCheckboxSelectMultiple()
}

模型:

class AssetClass(models.Model):
default_labels = models.ManyToManyField(Label, null=True, blank=True)
pass

M2M 引用域

class Label(models.Model):
explanation = models.CharField(null=True, max_length=63)
svgpreview = models.CharField(null=True, max_length=31)
def __unicode__(self):
return unicode(self.explanation)
pass

现在,{{ form.as_p }} 生成的 HTML 代码如下:

<li><label for="id_labels_0"><input type="checkbox" name="labels" value="1" id="id_labels_0" /> Consult owner before using</label></li>
<li><label for="id_labels_1"><input type="checkbox" name="labels" value="2" id="id_labels_1" /> This item is broken</label></li>

这意味着它显然使用了 __unicode__模型“标签”的渲染。我怎样才能在 Select 小部件中更改该行为,以便它使用不同的函数来填充它的选择?我试图以合理便携的方式打印 '<img src="{{label.svgpreview}}" alt="{{label.explanation}}"...>'在复选框旁边?

最佳答案

您将覆盖 forms.widgets.CheckboxSelectMultiple 类:

这是 CheckboxSelectMultiple 类及其渲染函数:

class CheckboxSelectMultiple(SelectMultiple):
def render(self, name, value, attrs=None, choices=()):
if value is None: value = []
has_id = attrs and 'id' in attrs
final_attrs = self.build_attrs(attrs, name=name)
output = [u'<ul>']
# Normalize to strings
str_values = set([force_unicode(v) for v in value])
for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
# If an ID attribute was given, add a numeric index as a suffix,
# so that the checkboxes don't all have the same ID attribute.
if has_id:
final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
label_for = u' for="%s"' % final_attrs['id']
else:
label_for = ''

cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
option_value = force_unicode(option_value)
rendered_cb = cb.render(name, option_value)
option_label = conditional_escape(force_unicode(option_label))
output.append(u'<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label))
output.append(u'</ul>')
return mark_safe(u'\n'.join(output))

那么你会做什么:

class MyCheckboxSelectMultiple(CheckboxSelectMultiple):
def render(self, name, value, attrs=None, choices=()):
#put your code to have custom checkbox control with icon
#...
output.append(u'<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label)) # especially you will be working on this line
#...

那么你使用widgets=CheckboxSelectMultiple()的地方就会变成widgets=MyCheckboxSelectMultiple()

关于Django CheckboxSelectMultiple 从 ModelForm 覆盖 'choices',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8693251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com