【问题标题】:Django forms: one choises field is a subset of other choises field. How to change subset dynamically?Django 表单:一个选择字段是另一个选择字段的子集。如何动态更改子集?
【发布时间】:2012-03-01 07:10:15
【问题描述】:

我有表单,用户选择机场,然后可以选择机场航站楼之一(通过 ForeignKey 的一对多关系)。

终端字段的选择必须受限于所选机场的终端。

有没有一些通用的方法来实现这个?

我现在关注ajax filtered fields library,但也许还有其他方法...

感谢小鸡!这里还有一个从数据库模型创建 data-parent 属性的链接: custom attributes in widget rendering

但在我的情况下,添加 data-parent 属性的解决方案更简单:

  1. 继承选择小部件属性并添加新信息:

    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)))
    
  2. 创建表单时填写终端端口字典:

    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)
    

【问题讨论】:

    标签: django jquery django-forms relationship


    【解决方案1】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 2012-01-21
    相关资源
    最近更新 更多