django表单无线电输入布局

django表单无线电输入布局,第1张

django表单无线电输入布局

安东的答案行之有效,并且在那儿是一个不错的答案-
但不幸的是,它变得难以维持。因此,从与django票#9230相连的差异中获取线索,我只是修补了猴子

django.forms.forms.BoundField

from django import formsdef MonkeyPatchDjangoFormsBoundField():    def prepare_widget_render(self, widget=None, attrs=None, only_initial=False):        """        Prepare the data needed for the widget rendering.        """        if not widget: widget = self.field.widget        attrs = attrs or {}        auto_id = self.auto_id        if auto_id and 'id' not in attrs and 'id' not in widget.attrs: if not only_initial:     attrs['id'] = auto_id else:     attrs['id'] = self.html_initial_id        if not only_initial: name = self.html_name        else: name = self.html_initial_name        return widget, name, attrs    def as_widget(self, widget=None, attrs=None, only_initial=False):        """        Renders the field by rendering the passed widget, adding any HTML        attributes passed as attrs.  If no widget is specified, then the        field's default widget will be used.        """        widget, name, attrs = self.prepare_widget_render(widget, attrs, only_initial)        return widget.render(name, self.value(), attrs=attrs)    def __iter__(self):        """        Check if current widget has a renderer and iterate renderer.        """        widget, name, attrs = self.prepare_widget_render()        if not hasattr(widget, 'get_renderer'): raise Exception, "Can not iterate over widget '%s'" % widget.__class__.__name__        renderer = widget.get_renderer(name, self.value(), attrs=attrs)        for entry in renderer: yield entry    def __getitem__(self,idx):        """        Tries to use current widget's renderer, and then check attribute.        """        widget, name, attrs = self.prepare_widget_render()        try: renderer = widget.get_renderer(name, self.value(), attrs=attrs) return renderer[idx]        except Exception: return getattr(self,idx)    forms.forms.BoundField.prepare_widget_render = prepare_widget_render    forms.forms.BoundField.as_widget = as_widget    forms.forms.BoundField.__iter__ = __iter__    forms.forms.BoundField.__getitem__ = __getitem__

这使我能够通过使用

{{ form.field.0.tag }}
或通过-直接访问无线电输入
{% for radio in form.field %}{{ radio.tag }} {% endfor %}
。保养起来容易得多!



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5674940.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存