I have form, where user selects Airport and then can select one of airport terminals (one to many relationship through ForeignKey).
Choises for terminal field must be limited by terminals of selected airport.
Is there some common way to implement this?
I watch now for ajax filtered fields library, but maybe there are some other ways...
Thanks to Chicko! And here one more link to create data-parent attribute from database model: custom attributes in widget rendering
But in my case solution for adding data-parent attribute is simplier:
Inherit select widget attribute and add new info:
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)))
Fill terminal-ports dictionary when create form:
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)