django - 替换 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
解决方案
所以我想出了答案。如果有人遇到同样的问题,会在这里发布。
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))
推荐阅读
- ruby-on-rails - 为递归模型创建表单
- php - 尝试使用 laravel 解析 xml 时出错
- mpi - 消息大小为 32 MiB 的 MPI 发送/接收延迟跳跃
- ios - 在 ARKit ARWorldMap 中保持对象方向
- javascript - Javascript 是否有类似于 python 的 dict 理解的东西?
- javascript - 有人可以用简单的英语解释我的对象代码的特定部分发生了什么吗?
- python - 使用 tkinter 单击更改按钮浮雕
- speech-to-text - Google Cloud Speech API 未返回所有文本
- javascript - 如何为数据表建模数据?
- java - Netty worker 和 boss 线程配置性能问题