我有表格,用户选择机场,然后可以选择一个机场航站楼(通过ForeignKey一对多关系)。
终端场的选择必须受所选机场的终端限制。
有没有一些常用的方法来实现它?
我现在关注ajax filtered fields library,但也许还有其他一些方法......
感谢Chicko!这里还有一个从数据库模型创建data-parent属性的链接: custom attributes in widget rendering
但在我的案例中,添加数据的方法 - 父属性更简单:
继承选择窗口小部件属性并添加新信息:
class TerminalSelect(forms.Select):
terminal_ports={}
def render_option(self, selected_choices, option_value, option_label):
if option_label in self.terminal_ports.keys():
airport=self.terminal_ports[option_label]
else:
airport=""
option_value = force_unicode(option_value)
selected_html = (option_value in selected_choices) and u' selected="selected"' or ''
return u'<option data-parent="%s" value="%s"%s>%s</option>' % (
airport, escape(option_value), selected_html,
conditional_escape(force_unicode(option_label)))
创建表单时填写终端端口字典:
airports_queryset=Airport.objects.all()
airport=forms.ModelChoiceField(queryset=airports_queryset)
terminals_queryset=AirportTerminal.objects.all()
terminal_ports={}
for terminal in terminals_queryset:
terminal_ports[force_unicode(terminal.name)]=force_unicode(terminal.airport.name)
terminal_select_widget=TerminalSelect()
terminal_select_widget.terminal_ports=terminal_ports
terminal=forms.ModelChoiceField(queryset=terminals_queryset,widget=terminal_select_widget)
答案 0 :(得分:0)