替换Django`render_options`

时间:2018-09-04 21:57:37

标签: django django-widget

因此,我正在实现以下答案:Country/State/City dropdown menus inside the Django admin inline,但是需要重做def render的代码段...。我已经成功地重做了,但是我正在努力寻找替代方法(或正确的代码)用于self.render_options类的Widget方法(在1.11版中已弃用)。

我使用的是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))

1 个答案:

答案 0 :(得分:0)

所以我想出了答案。如果有人遇到相同问题,将在此处发布。

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))