#NEWLINE# def __init__( self , * args , **kwargs ) : #NEWLINE# #INDENT# 'Accepts ``environments`` queryset and ``current`` env id.' #NEWLINE# environments = kwargs . pop ( 'environments' , [ ] ) #NEWLINE# current = kwargs . pop ( 'current' , None ) #NEWLINE# super ( EnvironmentSelectionForm , self ) . __init__ ( * args , ** kwargs ) #NEWLINE# self . categories = [ ] #NEWLINE# self . elements_by_category = { #NEWLINE# #INDENT# #NEWLINE# #UNINDENT# } #NEWLINE# self . elementids_by_envid = { #NEWLINE# #INDENT# #NEWLINE# #UNINDENT# } #NEWLINE# current_elements = [ ] #NEWLINE# env_element_through_model = model . Environment . elements . through #NEWLINE# env_element_relationships = env_element_through_model . objects . filter ( environment__in = environments ) . select_related ( ) #NEWLINE# cat_set = set ( ) #NEWLINE# for ee in env_element_relationships : #NEWLINE# #INDENT# cat_set . add ( ee . element . category ) #NEWLINE# if ( ee . environment . id == current ) : #NEWLINE# #INDENT# current_elements . append ( ee . element ) #NEWLINE# #UNINDENT# #UNINDENT# self . categories = sorted ( cat_set , key = ( lambda c : c . name ) ) #NEWLINE# num_categories = len ( self . categories ) #NEWLINE# for ee in env_element_relationships : #NEWLINE# #INDENT# byenv = self . elementids_by_envid . setdefault ( ee . environment . id , ( [ None ] * num_categories ) ) #NEWLINE# category_index = self . categories . index ( ee . element . category ) #NEWLINE# byenv [ category_index ] = ee . element . id #NEWLINE# bycat = self . elements_by_category . setdefault ( ee . element . category , set ( ) ) #NEWLINE# bycat . add ( ee . element ) #NEWLINE# #UNINDENT# for category in self . categories : #NEWLINE# #INDENT# self . fields [ 'category_{0}' . format ( category . id ) ] = forms . ChoiceField ( choices = ( [ ( '' , '---------' ) ] + [ ( e . id , e . name ) for e in sorted ( self . elements_by_category [ category ] , key = ( lambda e : e . name ) ) ] ) , label = category . name , required = False ) #NEWLINE# #UNINDENT# for element in current_elements : #NEWLINE# #INDENT# field_name = 'category_{0}' . format ( element . category . id ) #NEWLINE# self . initial [ field_name ] = element . id