【发布时间】:2011-07-30 08:00:04
【问题描述】:
我有一个 Location 模型和一个关联的表单,该表单将“位置”字段显示为一堆单选按钮(使用表单查询集来显示值)。有少量位置,但它们需要是动态的。我想在每个单选框选项旁边显示位置描述,以便用户获得有关位置的更多信息。
假设这是一个单选按钮列表,这就是我想要的样子:
东 - 这个位置在东。 West - 这是西部的位置! 北 - 这是北位置
我有一个类似于以下的模型:
class Location(models.Models):
location = models.CharField(max_length=50)
description = models.TextField(blank=True, null=True)
还有这样的形式:
class LocationForm(forms.Form):
location = ExtraModelChoiceField(
widget=RadioSelect(renderer=ExtraHorizRadioRenderer),
queryset = models.Locations.objects.filter(active=True))
我似乎找不到呈现表单的好方法,因此我可以将描述与每个选择选项一起显示。我做了很多压倒一切的事情,但运气不佳。
我尝试解决(但还没有成功):
据我所知,通常如果在表单字段上提供了一个查询集,Django 表单逻辑会将其转换为一个选择 tupal 的 tupal。每个“subtupal”都包含一个在渲染时显示的 id 和标签。我正在尝试为那些“subtupals”添加第三个值,这将是一个描述。
我已经定义了一个自定义渲染器来水平显示我的单选按钮并传入我的自定义选项。
class ExtraHorizRadioRenderer(forms.RadioSelect.renderer):
def render(self):
return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))
def __iter__(self):
for i, choice in enumerate(self.choices):
yield ExtraRadioInput(self.name, self.value,
self.attrs.copy(), choice, i)
def __getitem__(self, idx):
choice = self.choices[idx] # Let the IndexError propogate
return ExtraRadioInput(self.name, self.value,
self.attrs.copy(), choice, idx)
我已经覆盖了 Django RadioInput 类,因此我可以添加我需要在单选按钮旁边显示的描述信息。
class ExtraRadioInput(forms.widgets.RadioInput):
def __init__(self, name, value, attrs, choice, index):
self.name, self.value = name, value
self.attrs = attrs
self.choice_value = force_unicode(choice[0])
self.choice_label = force_unicode(choice[1])
self.choice_description = force_unicode(choice[2]) # <--- MY ADDITION; FAILS
self.index = index
def __unicode__(self):
if 'id' in self.attrs:
label_for = ' for="%s_%s"' % (self.attrs['id'], self.index)
else:
label_for = ''
choice_label = conditional_escape(force_unicode(self.choice_label))
return mark_safe(u'<label%s>%s %s</label>' % (
label_for, self.tag(), choice_label))
def tag(self):
if 'id' in self.attrs:
self.attrs['id'] = '%s_%s' % (self.attrs['id'], self.index)
final_attrs = dict(self.attrs, type='radio', name=self.name,
value=self.choice_value)
if self.is_checked():
final_attrs['checked'] = 'checked'
return mark_safe(
u'<input%s /><span class="description">%s</span>' % \
(flatatt(final_attrs),self.choice_description )) # <--- MY ADDTIONS
我还重写了以下两个 Django 类,希望传递我修改后的选择 tupal。
class ExtraModelChoiceIterator(forms.models.ModelChoiceIterator ):
def choice(self, obj):
if self.field.to_field_name:
key = obj.serializable_value(self.field.to_field_name)
else:
key = obj.pk
if obj.description: # <-- MY ADDITIONS
description = obj.description
else:
description = ""
return (key, self.field.label_from_instance(obj),description)
class ExtraModelChoiceField(forms.models.ModelChoiceField):
def _get_choices(self):
if hasattr(self, '_choices'):
return self._choices
return ExtraModelChoiceIterator(self) # <-- Uses MY NEW ITERATOR
使用上述方法,我似乎无法传递我的 3 值 tupal。我得到一个“元组索引超出范围”失败(我在上面标记 FAILURE 的地方)表明我的 tupal 不知何故没有额外的价值。
有没有人看到我的逻辑有缺陷,或者更一般地说,有一种方法可以使用小部件在选项列表旁边显示描述?
感谢阅读。任何 cmets 都非常感谢。 乔
【问题讨论】:
-
您是否考虑过只使用 CSS 来做到这一点?对我来说似乎容易多了。我觉得 Python/Django 开发人员不需要担心使用服务器端代码进行这样的格式化。
标签: django forms widget radio-button models