首页 > 解决方案 > 替换 django `render_options`

问题描述

所以我正在实现这个答案:Django admin inline 中的 Country/State/City 下拉菜单,但是def render需要重做这段代码......我已经设法重做它,但我正在努力寻找替代品(或类的self.render_options方法(在 1.11 中已弃用)的正确代码)Widget

我在 Django 2.1 上。我应该改变什么?这是我的代码:

class StateChoiceWidget(widgets.Select):
    def render(self, name, value, attrs=None, renderer=None):
        self.choices = [(u"", u"---------")]
        if value is None:
            value = ''
            model_obj = self.form_instance.instance
            if model_obj and model_obj.country:
                for m in model_obj.country.state_set.all():
                    self.choices.append((m.id, smart_text(m)))
        else: 
            obj = State.objects.get(id=value)
            for m in State.objects.filter(country=obj.country):
                self.choices.append((m.id, smart_text(m)))

        final_attrs = self.build_attrs(attrs)
        output = ['<select%s>' % flatatt(final_attrs)]
        for option in self.choices:
            output.append('<option value="%s">%s</option>' % (option[0], option[1]))
        output.append('</select>')
        return mark_safe(''.join(output))

原始海报更新了示例代码,所以现在它没有显示问题中的代码:请参阅以前的修订版https://stackoverflow.com/revisions/52174508/1

标签: djangodjango-widget

解决方案


所以我想出了答案。如果有人遇到同样的问题,会在这里发布。

class StateChoiceWidget(widgets.Select):
    def render(self, name, value, attrs=None, renderer=None):
        self.choices = [(u"", u"---------")]
        if value is None or value == '':
            value = ''
            model_obj = self.form_instance.instance
            if model_obj and model_obj.country:
                for m in model_obj.country.state_set.all():
                    self.choices.append((m.id, smart_text(m)))
        else: 
            obj = State.objects.get(id=value)
            for m in State.objects.filter(country=obj.country):
                self.choices.append((m.id, smart_text(m)))

        final_attrs = self.build_attrs(attrs) 

        s = widgets.Select(choices=self.choices)
        select_html = s.render(name=name,value=value,attrs=attrs)

        return mark_safe(''.join(select_html))

推荐阅读