私は、ユーザーがAirportを選択し、次に空港ターミナルの1つを選択することができるフォームを持っています(ForeignKeyで1対多数の関係)。Djangoフォーム:1つのchoisesフィールドは、他のchoisesフィールドのサブセットです。サブセットを動的に変更するには?
端末フィールドの選択は、選択した空港の端末によって制限される必要があります。
これを実装する一般的な方法はありますか?
Chickoへ
おかげで...私はajax filtered fields libraryのために今見て、多分他のいくつかの方法があります!そして、ここでデータベースモデルからデータ・親属性を作成するための1つの以上のリンク: custom attributes in widget rendering
をしかし、私の場合には、データ・親属性を追加するためのソリューションはsimplierです:
継承は、ウィジェット属性を選択して、新しい情報を追加:
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)