<s> """<STR_LIT>""" <EOL> from __future__ import absolute_import <EOL> from django . core . exceptions import ValidationError , NON_FIELD_ERRORS , FieldError <EOL> from django . core . validators import EMPTY_VALUES <EOL> from django . forms . fields import Field , ChoiceField <EOL> from django . forms . forms import BaseForm , get_declared_fields <EOL> from django . forms . formsets import BaseFormSet , formset_factory <EOL> from django . forms . util import ErrorList <EOL> from django . forms . widgets import ( SelectMultiple , HiddenInput , <EOL> MultipleHiddenInput , media_property ) <EOL> from django . utils . encoding import smart_unicode , force_unicode <EOL> from django . utils . datastructures import SortedDict <EOL> from django . utils . text import get_text_list , capfirst <EOL> from django . utils . translation import ugettext_lazy as _ , ugettext <EOL> __all__ = ( <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> ) <EOL> def construct_instance ( form , instance , fields = None , exclude = None ) : <EOL> """<STR_LIT>""" <EOL> from django . db import models <EOL> opts = instance . _meta <EOL> cleaned_data = form . cleaned_data <EOL> file_field_list = [ ] <EOL> for f in opts . fields : <EOL> if not f . editable or isinstance ( f , models . AutoField ) or not f . name in cleaned_data : <EOL> continue <EOL> if fields is not None and f . name not in fields : <EOL> continue <EOL> if exclude and f . name in exclude : <EOL> continue <EOL> if isinstance ( f , models . FileField ) : <EOL> file_field_list . append ( f ) <EOL> else : <EOL> f . save_form_data ( instance , cleaned_data [ f . name ] ) <EOL> for f in file_field_list : <EOL> f . save_form_data ( instance , cleaned_data [ f . name ] ) <EOL> return instance <EOL> def save_instance ( form , instance , fields = None , fail_message = '<STR_LIT>' , <EOL> commit = True , exclude = None , construct = True ) : <EOL> """<STR_LIT>""" <EOL> if construct : <EOL> instance = construct_instance ( form , instance , fields , exclude ) <EOL> opts = instance . _meta <EOL> if form . errors : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" % ( opts . object_name , fail_message ) ) <EOL> def save_m2m ( ) : <EOL> cleaned_data = form . cleaned_data <EOL> for f in opts . many_to_many : <EOL> if fields and f . name not in fields : <EOL> continue <EOL> if f . name in cleaned_data : <EOL> f . save_form_data ( instance , cleaned_data [ f . name ] ) <EOL> if commit : <EOL> instance . save ( ) <EOL> save_m2m ( ) <EOL> else : <EOL> form . save_m2m = save_m2m <EOL> return instance <EOL> def model_to_dict ( instance , fields = None , exclude = None ) : <EOL> """<STR_LIT>""" <EOL> from django . db . models . fields . related import ManyToManyField <EOL> opts = instance . _meta <EOL> data = { } <EOL> for f in opts . fields + opts . many_to_many : <EOL> if not f . editable : <EOL> continue <EOL> if fields and not f . name in fields : <EOL> continue <EOL> if exclude and f . name in exclude : <EOL> continue <EOL> if isinstance ( f , ManyToManyField ) : <EOL> if instance . pk is None : <EOL> data [ f . name ] = [ ] <EOL> else : <EOL> data [ f . name ] = [ obj . pk for obj in f . value_from_object ( instance ) ] <EOL> else : <EOL> data [ f . name ] = f . value_from_object ( instance ) <EOL> return data <EOL> def fields_for_model ( model , fields = None , exclude = None , widgets = None , formfield_callback = None ) : <EOL> """<STR_LIT>""" <EOL> field_list = [ ] <EOL> ignored = [ ] <EOL> opts = model . _meta <EOL> for f in sorted ( opts . fields + opts . many_to_many ) : <EOL> if not f . editable : <EOL> continue <EOL> if fields is not None and not f . name in fields : <EOL> continue <EOL> if exclude and f . name in exclude : <EOL> continue <EOL> if widgets and f . name in widgets : <EOL> kwargs = { '<STR_LIT>' : widgets [ f . name ] } <EOL> else : <EOL> kwargs = { } <EOL> if formfield_callback is None : <EOL> formfield = f . formfield ( ** kwargs ) <EOL> elif not callable ( formfield_callback ) : <EOL> raise TypeError ( '<STR_LIT>' ) <EOL> else : <EOL> formfield = formfield_callback ( f , ** kwargs ) <EOL> if formfield : <EOL> field_list . append ( ( f . name , formfield ) ) <EOL> else : <EOL> ignored . append ( f . name ) <EOL> field_dict = SortedDict ( field_list ) <EOL> if fields : <EOL> field_dict = SortedDict ( <EOL> [ ( f , field_dict . get ( f ) ) for f in fields <EOL> if ( ( not exclude ) or ( exclude and f not in exclude ) ) and ( f not in ignored ) ] <EOL> ) <EOL> return field_dict <EOL> class ModelFormOptions ( object ) : <EOL> def __init__ ( self , options = None ) : <EOL> self . model = getattr ( options , '<STR_LIT>' , None ) <EOL> self . fields = getattr ( options , '<STR_LIT>' , None ) <EOL> self . exclude = getattr ( options , '<STR_LIT>' , None ) <EOL> self . widgets = getattr ( options , '<STR_LIT>' , None ) <EOL> class ModelFormMetaclass ( type ) : <EOL> def __new__ ( cls , name , bases , attrs ) : <EOL> formfield_callback = attrs . pop ( '<STR_LIT>' , None ) <EOL> try : <EOL> parents = [ b for b in bases if issubclass ( b , ModelForm ) ] <EOL> except NameError : <EOL> parents = None <EOL> declared_fields = get_declared_fields ( bases , attrs , False ) <EOL> new_class = super ( ModelFormMetaclass , cls ) . __new__ ( cls , name , bases , <EOL> attrs ) <EOL> if not parents : <EOL> return new_class <EOL> if '<STR_LIT>' not in attrs : <EOL> new_class . media = media_property ( new_class ) <EOL> opts = new_class . _meta = ModelFormOptions ( getattr ( new_class , '<STR_LIT:Meta>' , None ) ) <EOL> if opts . model : <EOL> fields = fields_for_model ( opts . model , opts . fields , <EOL> opts . exclude , opts . widgets , formfield_callback ) <EOL> none_model_fields = [ k for k , v in fields . iteritems ( ) if not v ] <EOL> missing_fields = set ( none_model_fields ) - set ( declared_fields . keys ( ) ) <EOL> if missing_fields : <EOL> message = '<STR_LIT>' <EOL> message = message % ( '<STR_LIT:U+002CU+0020>' . join ( missing_fields ) , <EOL> opts . model . __name__ ) <EOL> raise FieldError ( message ) <EOL> fields . update ( declared_fields ) <EOL> else : <EOL> fields = declared_fields <EOL> new_class . declared_fields = declared_fields <EOL> new_class . base_fields = fields <EOL> return new_class <EOL> class BaseModelForm ( BaseForm ) : <EOL> def __init__ ( self , data = None , files = None , auto_id = '<STR_LIT>' , prefix = None , <EOL> initial = None , error_class = ErrorList , label_suffix = '<STR_LIT::>' , <EOL> empty_permitted = False , instance = None ) : <EOL> opts = self . _meta <EOL> if instance is None : <EOL> if opts . model is None : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> self . instance = opts . model ( ) <EOL> object_data = { } <EOL> else : <EOL> self . instance = instance <EOL> object_data = model_to_dict ( instance , opts . fields , opts . exclude ) <EOL> if initial is not None : <EOL> object_data . update ( initial ) <EOL> self . _validate_unique = False <EOL> super ( BaseModelForm , self ) . __init__ ( data , files , auto_id , prefix , object_data , <EOL> error_class , label_suffix , empty_permitted ) <EOL> def _update_errors ( self , message_dict ) : <EOL> for k , v in message_dict . items ( ) : <EOL> if k != NON_FIELD_ERRORS : <EOL> self . _errors . setdefault ( k , self . error_class ( ) ) . extend ( v ) <EOL> if k in self . cleaned_data : <EOL> del self . cleaned_data [ k ] <EOL> if NON_FIELD_ERRORS in message_dict : <EOL> messages = message_dict [ NON_FIELD_ERRORS ] <EOL> self . _errors . setdefault ( NON_FIELD_ERRORS , self . error_class ( ) ) . extend ( messages ) <EOL> def _get_validation_exclusions ( self ) : <EOL> """<STR_LIT>""" <EOL> exclude = [ ] <EOL> for f in self . instance . _meta . fields : <EOL> field = f . name <EOL> if field not in self . fields : <EOL> exclude . append ( f . name ) <EOL> elif self . _meta . fields and field not in self . _meta . fields : <EOL> exclude . append ( f . name ) <EOL> elif self . _meta . exclude and field in self . _meta . exclude : <EOL> exclude . append ( f . name ) <EOL> elif field in self . _errors . keys ( ) : <EOL> exclude . append ( f . name ) <EOL> else : <EOL> form_field = self . fields [ field ] <EOL> field_value = self . cleaned_data . get ( field , None ) <EOL> if not f . blank and not form_field . required and field_value in EMPTY_VALUES : <EOL> exclude . append ( f . name ) <EOL> return exclude <EOL> def clean ( self ) : <EOL> self . _validate_unique = True <EOL> return self . cleaned_data <EOL> def _post_clean ( self ) : <EOL> opts = self . _meta <EOL> self . instance = construct_instance ( self , self . instance , opts . fields , opts . exclude ) <EOL> exclude = self . _get_validation_exclusions ( ) <EOL> for f_name , field in self . fields . items ( ) : <EOL> if isinstance ( field , InlineForeignKeyField ) : <EOL> exclude . append ( f_name ) <EOL> try : <EOL> self . instance . clean_fields ( exclude = exclude ) <EOL> except ValidationError , e : <EOL> self . _update_errors ( e . message_dict ) <EOL> try : <EOL> self . instance . clean ( ) <EOL> except ValidationError , e : <EOL> self . _update_errors ( { NON_FIELD_ERRORS : e . messages } ) <EOL> if self . _validate_unique : <EOL> self . validate_unique ( ) <EOL> def validate_unique ( self ) : <EOL> """<STR_LIT>""" <EOL> exclude = self . _get_validation_exclusions ( ) <EOL> try : <EOL> self . instance . validate_unique ( exclude = exclude ) <EOL> except ValidationError , e : <EOL> self . _update_errors ( e . message_dict ) <EOL> def save ( self , commit = True ) : <EOL> """<STR_LIT>""" <EOL> if self . instance . pk is None : <EOL> fail_message = '<STR_LIT>' <EOL> else : <EOL> fail_message = '<STR_LIT>' <EOL> return save_instance ( self , self . instance , self . _meta . fields , <EOL> fail_message , commit , construct = False ) <EOL> save . alters_data = True <EOL> class ModelForm ( BaseModelForm ) : <EOL> __metaclass__ = ModelFormMetaclass <EOL> def modelform_factory ( model , form = ModelForm , fields = None , exclude = None , <EOL> formfield_callback = None , widgets = None ) : <EOL> attrs = { '<STR_LIT>' : model } <EOL> if fields is not None : <EOL> attrs [ '<STR_LIT>' ] = fields <EOL> if exclude is not None : <EOL> attrs [ '<STR_LIT>' ] = exclude <EOL> if widgets is not None : <EOL> attrs [ '<STR_LIT>' ] = widgets <EOL> parent = ( object , ) <EOL> if hasattr ( form , '<STR_LIT:Meta>' ) : <EOL> parent = ( form . Meta , object ) <EOL> Meta = type ( '<STR_LIT:Meta>' , parent , attrs ) <EOL> class_name = model . __name__ + '<STR_LIT>' <EOL> form_class_attrs = { <EOL> '<STR_LIT:Meta>' : Meta , <EOL> '<STR_LIT>' : formfield_callback <EOL> } <EOL> form_metaclass = ModelFormMetaclass <EOL> if issubclass ( form , BaseModelForm ) and hasattr ( form , '<STR_LIT>' ) : <EOL> form_metaclass = form . __metaclass__ <EOL> return form_metaclass ( class_name , ( form , ) , form_class_attrs ) <EOL> class BaseModelFormSet ( BaseFormSet ) : <EOL> """<STR_LIT>""" <EOL> model = None <EOL> def __init__ ( self , data = None , files = None , auto_id = '<STR_LIT>' , prefix = None , <EOL> queryset = None , ** kwargs ) : <EOL> self . queryset = queryset <EOL> self . initial_extra = kwargs . pop ( '<STR_LIT>' , None ) <EOL> defaults = { '<STR_LIT:data>' : data , '<STR_LIT>' : files , '<STR_LIT>' : auto_id , '<STR_LIT>' : prefix } <EOL> defaults . update ( kwargs ) <EOL> super ( BaseModelFormSet , self ) . __init__ ( ** defaults ) <EOL> def initial_form_count ( self ) : <EOL> """<STR_LIT>""" <EOL> if not ( self . data or self . files ) : <EOL> return len ( self . get_queryset ( ) ) <EOL> return super ( BaseModelFormSet , self ) . initial_form_count ( ) <EOL> def _existing_object ( self , pk ) : <EOL> if not hasattr ( self , '<STR_LIT>' ) : <EOL> self . _object_dict = dict ( [ ( o . pk , o ) for o in self . get_queryset ( ) ] ) <EOL> return self . _object_dict . get ( pk ) <EOL> def _construct_form ( self , i , ** kwargs ) : <EOL> if self . is_bound and i < self . initial_form_count ( ) : <EOL> from django . db import connections <EOL> pk_key = "<STR_LIT>" % ( self . add_prefix ( i ) , self . model . _meta . pk . name ) <EOL> pk = self . data [ pk_key ] <EOL> pk_field = self . model . _meta . pk <EOL> pk = pk_field . get_db_prep_lookup ( '<STR_LIT>' , pk , <EOL> connection = connections [ self . get_queryset ( ) . db ] ) <EOL> if isinstance ( pk , list ) : <EOL> pk = pk [ <NUM_LIT:0> ] <EOL> kwargs [ '<STR_LIT>' ] = self . _existing_object ( pk ) <EOL> if i < self . initial_form_count ( ) and not kwargs . get ( '<STR_LIT>' ) : <EOL> kwargs [ '<STR_LIT>' ] = self . get_queryset ( ) [ i ] <EOL> if i >= self . initial_form_count ( ) and self . initial_extra : <EOL> try : <EOL> kwargs [ '<STR_LIT>' ] = self . initial_extra [ i - self . initial_form_count ( ) ] <EOL> except IndexError : <EOL> pass <EOL> return super ( BaseModelFormSet , self ) . _construct_form ( i , ** kwargs ) <EOL> def get_queryset ( self ) : <EOL> if not hasattr ( self , '<STR_LIT>' ) : <EOL> if self . queryset is not None : <EOL> qs = self . queryset <EOL> else : <EOL> qs = self . model . _default_manager . get_query_set ( ) <EOL> if not qs . ordered : <EOL> qs = qs . order_by ( self . model . _meta . pk . name ) <EOL> self . _queryset = qs <EOL> return self . _queryset <EOL> def save_new ( self , form , commit = True ) : <EOL> """<STR_LIT>""" <EOL> return form . save ( commit = commit ) <EOL> def save_existing ( self , form , instance , commit = True ) : <EOL> """<STR_LIT>""" <EOL> return form . save ( commit = commit ) <EOL> def save ( self , commit = True ) : <EOL> """<STR_LIT>""" <EOL> if not commit : <EOL> self . saved_forms = [ ] <EOL> def save_m2m ( ) : <EOL> for form in self . saved_forms : <EOL> form . save_m2m ( ) <EOL> self . save_m2m = save_m2m <EOL> return self . save_existing_objects ( commit ) + self . save_new_objects ( commit ) <EOL> def clean ( self ) : <EOL> self . validate_unique ( ) <EOL> def validate_unique ( self ) : <EOL> all_unique_checks = set ( ) <EOL> all_date_checks = set ( ) <EOL> for form in self . forms : <EOL> if not hasattr ( form , '<STR_LIT>' ) : <EOL> continue <EOL> exclude = form . _get_validation_exclusions ( ) <EOL> unique_checks , date_checks = form . instance . _get_unique_checks ( exclude = exclude ) <EOL> all_unique_checks = all_unique_checks . union ( set ( unique_checks ) ) <EOL> all_date_checks = all_date_checks . union ( set ( date_checks ) ) <EOL> errors = [ ] <EOL> for uclass , unique_check in all_unique_checks : <EOL> seen_data = set ( ) <EOL> for form in self . forms : <EOL> if not hasattr ( form , "<STR_LIT>" ) : <EOL> continue <EOL> row_data = tuple ( [ form . cleaned_data [ field ] for field in unique_check if field in form . cleaned_data ] ) <EOL> if row_data and not None in row_data : <EOL> if row_data in seen_data : <EOL> errors . append ( self . get_unique_error_message ( unique_check ) ) <EOL> form . _errors [ NON_FIELD_ERRORS ] = self . error_class ( [ self . get_form_error ( ) ] ) <EOL> del form . cleaned_data <EOL> break <EOL> seen_data . add ( row_data ) <EOL> for date_check in all_date_checks : <EOL> seen_data = set ( ) <EOL> uclass , lookup , field , unique_for = date_check <EOL> for form in self . forms : <EOL> if not hasattr ( self , '<STR_LIT>' ) : <EOL> continue <EOL> if ( form . cleaned_data and form . cleaned_data [ field ] is not None <EOL> and form . cleaned_data [ unique_for ] is not None ) : <EOL> if lookup == '<STR_LIT:date>' : <EOL> date = form . cleaned_data [ unique_for ] <EOL> date_data = ( date . year , date . month , date . day ) <EOL> else : <EOL> date_data = ( getattr ( form . cleaned_data [ unique_for ] , lookup ) , ) <EOL> data = ( form . cleaned_data [ field ] , ) + date_data <EOL> if data in seen_data : <EOL> errors . append ( self . get_date_error_message ( date_check ) ) <EOL> form . _errors [ NON_FIELD_ERRORS ] = self . error_class ( [ self . get_form_error ( ) ] ) <EOL> del form . cleaned_data <EOL> break <EOL> seen_data . add ( data ) <EOL> if errors : <EOL> raise ValidationError ( errors ) <EOL> def get_unique_error_message ( self , unique_check ) : <EOL> if len ( unique_check ) == <NUM_LIT:1> : <EOL> return ugettext ( "<STR_LIT>" ) % { <EOL> "<STR_LIT>" : unique_check [ <NUM_LIT:0> ] , <EOL> } <EOL> else : <EOL> return ugettext ( "<STR_LIT>" <EOL> "<STR_LIT>" ) % { <EOL> "<STR_LIT>" : get_text_list ( unique_check , unicode ( _ ( "<STR_LIT>" ) ) ) , <EOL> } <EOL> def get_date_error_message ( self , date_check ) : <EOL> return ugettext ( "<STR_LIT>" <EOL> "<STR_LIT>" ) % { <EOL> '<STR_LIT>' : date_check [ <NUM_LIT:2> ] , <EOL> '<STR_LIT>' : date_check [ <NUM_LIT:3> ] , <EOL> '<STR_LIT>' : unicode ( date_check [ <NUM_LIT:1> ] ) , <EOL> } <EOL> def get_form_error ( self ) : <EOL> return ugettext ( "<STR_LIT>" ) <EOL> def save_existing_objects ( self , commit = True ) : <EOL> self . changed_objects = [ ] <EOL> self . deleted_objects = [ ] <EOL> if not self . initial_forms : <EOL> return [ ] <EOL> saved_instances = [ ] <EOL> for form in self . initial_forms : <EOL> pk_name = self . _pk_field . name <EOL> raw_pk_value = form . _raw_value ( pk_name ) <EOL> pk_value = form . fields [ pk_name ] . clean ( raw_pk_value ) <EOL> pk_value = getattr ( pk_value , '<STR_LIT>' , pk_value ) <EOL> obj = self . _existing_object ( pk_value ) <EOL> if self . can_delete and self . _should_delete_form ( form ) : <EOL> self . deleted_objects . append ( obj ) <EOL> obj . delete ( ) <EOL> continue <EOL> if form . has_changed ( ) : <EOL> self . changed_objects . append ( ( obj , form . changed_data ) ) <EOL> saved_instances . append ( self . save_existing ( form , obj , commit = commit ) ) <EOL> if not commit : <EOL> self . saved_forms . append ( form ) <EOL> return saved_instances <EOL> def save_new_objects ( self , commit = True ) : <EOL> self . new_objects = [ ] <EOL> for form in self . extra_forms : <EOL> if not form . has_changed ( ) : <EOL> continue <EOL> if self . can_delete and self . _should_delete_form ( form ) : <EOL> continue <EOL> self . new_objects . append ( self . save_new ( form , commit = commit ) ) <EOL> if not commit : <EOL> self . saved_forms . append ( form ) <EOL> return self . new_objects <EOL> def add_fields ( self , form , index ) : <EOL> """<STR_LIT>""" <EOL> from django . db . models import AutoField , OneToOneField , ForeignKey <EOL> self . _pk_field = pk = self . model . _meta . pk <EOL> def pk_is_not_editable ( pk ) : <EOL> return ( ( not pk . editable ) or ( pk . auto_created or isinstance ( pk , AutoField ) ) <EOL> or ( pk . rel and pk . rel . parent_link and pk_is_not_editable ( pk . rel . to . _meta . pk ) ) ) <EOL> if pk_is_not_editable ( pk ) or pk . name not in form . fields : <EOL> if form . is_bound : <EOL> pk_value = form . instance . pk <EOL> else : <EOL> try : <EOL> if index is not None : <EOL> pk_value = self . get_queryset ( ) [ index ] . pk <EOL> else : <EOL> pk_value = None <EOL> except IndexError : <EOL> pk_value = None <EOL> if isinstance ( pk , OneToOneField ) or isinstance ( pk , ForeignKey ) : <EOL> qs = pk . rel . to . _default_manager . get_query_set ( ) <EOL> else : <EOL> qs = self . model . _default_manager . get_query_set ( ) <EOL> qs = qs . using ( form . instance . _state . db ) <EOL> form . fields [ self . _pk_field . name ] = ModelChoiceField ( qs , initial = pk_value , required = False , widget = HiddenInput ) <EOL> super ( BaseModelFormSet , self ) . add_fields ( form , index ) <EOL> def modelformset_factory ( model , form = ModelForm , formfield_callback = None , <EOL> formset = BaseModelFormSet , <EOL> extra = <NUM_LIT:1> , can_delete = False , can_order = False , <EOL> max_num = None , fields = None , exclude = None ) : <EOL> """<STR_LIT>""" <EOL> form = modelform_factory ( model , form = form , fields = fields , exclude = exclude , <EOL> formfield_callback = formfield_callback ) <EOL> FormSet = formset_factory ( form , formset , extra = extra , max_num = max_num , <EOL> can_order = can_order , can_delete = can_delete ) <EOL> FormSet . model = model <EOL> return FormSet <EOL> class BaseInlineFormSet ( BaseModelFormSet ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , data = None , files = None , instance = None , <EOL> save_as_new = False , prefix = None , queryset = None , ** kwargs ) : <EOL> from django . db . models . fields . related import RelatedObject <EOL> if instance is None : <EOL> self . instance = self . fk . rel . to ( ) <EOL> else : <EOL> self . instance = instance <EOL> self . save_as_new = save_as_new <EOL> self . rel_name = RelatedObject ( self . fk . rel . to , self . model , self . fk ) . get_accessor_name ( ) <EOL> if queryset is None : <EOL> queryset = self . model . _default_manager <EOL> qs = queryset . filter ( ** { self . fk . name : self . instance } ) <EOL> super ( BaseInlineFormSet , self ) . __init__ ( data , files , prefix = prefix , <EOL> queryset = qs , ** kwargs ) <EOL> def initial_form_count ( self ) : <EOL> if self . save_as_new : <EOL> return <NUM_LIT:0> <EOL> return super ( BaseInlineFormSet , self ) . initial_form_count ( ) <EOL> def _construct_form ( self , i , ** kwargs ) : <EOL> form = super ( BaseInlineFormSet , self ) . _construct_form ( i , ** kwargs ) <EOL> if self . save_as_new : <EOL> form . data [ form . add_prefix ( self . _pk_field . name ) ] = None <EOL> form . data [ form . add_prefix ( self . fk . name ) ] = None <EOL> setattr ( form . instance , self . fk . get_attname ( ) , self . instance . pk ) <EOL> return form <EOL> @ classmethod <EOL> def get_default_prefix ( cls ) : <EOL> from django . db . models . fields . related import RelatedObject <EOL> return RelatedObject ( cls . fk . rel . to , cls . model , cls . fk ) . get_accessor_name ( ) . replace ( '<STR_LIT:+>' , '<STR_LIT>' ) <EOL> def save_new ( self , form , commit = True ) : <EOL> obj = form . save ( commit = False ) <EOL> pk_value = getattr ( self . instance , self . fk . rel . field_name ) <EOL> setattr ( obj , self . fk . get_attname ( ) , getattr ( pk_value , '<STR_LIT>' , pk_value ) ) <EOL> if commit : <EOL> obj . save ( ) <EOL> if commit and hasattr ( form , '<STR_LIT>' ) : <EOL> form . save_m2m ( ) <EOL> return obj <EOL> def add_fields ( self , form , index ) : <EOL> super ( BaseInlineFormSet , self ) . add_fields ( form , index ) <EOL> if self . _pk_field == self . fk : <EOL> name = self . _pk_field . name <EOL> kwargs = { '<STR_LIT>' : True } <EOL> else : <EOL> name = self . fk . name <EOL> kwargs = { <EOL> '<STR_LIT:label>' : getattr ( form . fields . get ( name ) , '<STR_LIT:label>' , capfirst ( self . fk . verbose_name ) ) <EOL> } <EOL> if self . fk . rel . field_name != self . fk . rel . to . _meta . pk . name : <EOL> kwargs [ '<STR_LIT>' ] = self . fk . rel . field_name <EOL> form . fields [ name ] = InlineForeignKeyField ( self . instance , ** kwargs ) <EOL> if form . _meta . fields : <EOL> if isinstance ( form . _meta . fields , tuple ) : <EOL> form . _meta . fields = list ( form . _meta . fields ) <EOL> form . _meta . fields . append ( self . fk . name ) <EOL> def get_unique_error_message ( self , unique_check ) : <EOL> unique_check = [ field for field in unique_check if field != self . fk . name ] <EOL> return super ( BaseInlineFormSet , self ) . get_unique_error_message ( unique_check ) <EOL> def _get_foreign_key ( parent_model , model , fk_name = None , can_fail = False ) : <EOL> """<STR_LIT>""" <EOL> from django . db . models import ForeignKey <EOL> opts = model . _meta <EOL> if fk_name : <EOL> fks_to_parent = [ f for f in opts . fields if f . name == fk_name ] <EOL> if len ( fks_to_parent ) == <NUM_LIT:1> : <EOL> fk = fks_to_parent [ <NUM_LIT:0> ] <EOL> if not isinstance ( fk , ForeignKey ) or ( fk . rel . to != parent_model and <EOL> fk . rel . to not in parent_model . _meta . get_parent_list ( ) ) : <EOL> raise Exception ( "<STR_LIT>" % ( fk_name , parent_model ) ) <EOL> elif len ( fks_to_parent ) == <NUM_LIT:0> : <EOL> raise Exception ( "<STR_LIT>" % ( model , fk_name ) ) <EOL> else : <EOL> fks_to_parent = [ <EOL> f for f in opts . fields <EOL> if isinstance ( f , ForeignKey ) <EOL> and ( f . rel . to == parent_model <EOL> or f . rel . to in parent_model . _meta . get_parent_list ( ) ) <EOL> ] <EOL> if len ( fks_to_parent ) == <NUM_LIT:1> : <EOL> fk = fks_to_parent [ <NUM_LIT:0> ] <EOL> elif len ( fks_to_parent ) == <NUM_LIT:0> : <EOL> if can_fail : <EOL> return <EOL> raise Exception ( "<STR_LIT>" % ( model , parent_model ) ) <EOL> else : <EOL> raise Exception ( "<STR_LIT>" % ( model , parent_model ) ) <EOL> return fk <EOL> def inlineformset_factory ( parent_model , model , form = ModelForm , <EOL> formset = BaseInlineFormSet , fk_name = None , <EOL> fields = None , exclude = None , <EOL> extra = <NUM_LIT:3> , can_order = False , can_delete = True , max_num = None , <EOL> formfield_callback = None ) : <EOL> """<STR_LIT>""" <EOL> fk = _get_foreign_key ( parent_model , model , fk_name = fk_name ) <EOL> if fk . unique : <EOL> max_num = <NUM_LIT:1> <EOL> kwargs = { <EOL> '<STR_LIT>' : form , <EOL> '<STR_LIT>' : formfield_callback , <EOL> '<STR_LIT>' : formset , <EOL> '<STR_LIT>' : extra , <EOL> '<STR_LIT>' : can_delete , <EOL> '<STR_LIT>' : can_order , <EOL> '<STR_LIT>' : fields , <EOL> '<STR_LIT>' : exclude , <EOL> '<STR_LIT>' : max_num , <EOL> } <EOL> FormSet = modelformset_factory ( model , ** kwargs ) <EOL> FormSet . fk = fk <EOL> return FormSet <EOL> class InlineForeignKeyHiddenInput ( HiddenInput ) : <EOL> def _has_changed ( self , initial , data ) : <EOL> return False <EOL> class InlineForeignKeyField ( Field ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' ) , <EOL> } <EOL> def __init__ ( self , parent_instance , * args , ** kwargs ) : <EOL> self . parent_instance = parent_instance <EOL> self . pk_field = kwargs . pop ( "<STR_LIT>" , False ) <EOL> self . to_field = kwargs . pop ( "<STR_LIT>" , None ) <EOL> if self . parent_instance is not None : <EOL> if self . to_field : <EOL> kwargs [ "<STR_LIT>" ] = getattr ( self . parent_instance , self . to_field ) <EOL> else : <EOL> kwargs [ "<STR_LIT>" ] = self . parent_instance . pk <EOL> kwargs [ "<STR_LIT>" ] = False <EOL> kwargs [ "<STR_LIT>" ] = InlineForeignKeyHiddenInput <EOL> super ( InlineForeignKeyField , self ) . __init__ ( * args , ** kwargs ) <EOL> def clean ( self , value ) : <EOL> if value in EMPTY_VALUES : <EOL> if self . pk_field : <EOL> return None <EOL> return self . parent_instance <EOL> if self . to_field : <EOL> orig = getattr ( self . parent_instance , self . to_field ) <EOL> else : <EOL> orig = self . parent_instance . pk <EOL> if force_unicode ( value ) != force_unicode ( orig ) : <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT>' ] ) <EOL> return self . parent_instance <EOL> class ModelChoiceIterator ( object ) : <EOL> def __init__ ( self , field ) : <EOL> self . field = field <EOL> self . queryset = field . queryset <EOL> def __iter__ ( self ) : <EOL> if self . field . empty_label is not None : <EOL> yield ( u"<STR_LIT>" , self . field . empty_label ) <EOL> if self . field . cache_choices : <EOL> if self . field . choice_cache is None : <EOL> self . field . choice_cache = [ <EOL> self . choice ( obj ) for obj in self . queryset . all ( ) <EOL> ] <EOL> for choice in self . field . choice_cache : <EOL> yield choice <EOL> else : <EOL> for obj in self . queryset . all ( ) : <EOL> yield self . choice ( obj ) <EOL> def __len__ ( self ) : <EOL> return len ( self . queryset ) <EOL> def choice ( self , obj ) : <EOL> return ( self . field . prepare_value ( obj ) , self . field . label_from_instance ( obj ) ) <EOL> class ModelChoiceField ( ChoiceField ) : <EOL> """<STR_LIT>""" <EOL> default_error_messages = { <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' <EOL> u'<STR_LIT>' ) , <EOL> } <EOL> def __init__ ( self , queryset , empty_label = u"<STR_LIT>" , cache_choices = False , <EOL> required = True , widget = None , label = None , initial = None , <EOL> help_text = None , to_field_name = None , * args , ** kwargs ) : <EOL> if required and ( initial is not None ) : <EOL> self . empty_label = None <EOL> else : <EOL> self . empty_label = empty_label <EOL> self . cache_choices = cache_choices <EOL> Field . __init__ ( self , required , widget , label , initial , help_text , <EOL> * args , ** kwargs ) <EOL> self . queryset = queryset <EOL> self . choice_cache = None <EOL> self . to_field_name = to_field_name <EOL> def __deepcopy__ ( self , memo ) : <EOL> result = super ( ChoiceField , self ) . __deepcopy__ ( memo ) <EOL> result . queryset = result . queryset <EOL> return result <EOL> def _get_queryset ( self ) : <EOL> return self . _queryset <EOL> def _set_queryset ( self , queryset ) : <EOL> self . _queryset = queryset <EOL> self . widget . choices = self . choices <EOL> queryset = property ( _get_queryset , _set_queryset ) <EOL> def label_from_instance ( self , obj ) : <EOL> """<STR_LIT>""" <EOL> return smart_unicode ( obj ) <EOL> def _get_choices ( self ) : <EOL> if hasattr ( self , '<STR_LIT>' ) : <EOL> return self . _choices <EOL> return ModelChoiceIterator ( self ) <EOL> choices = property ( _get_choices , ChoiceField . _set_choices ) <EOL> def prepare_value ( self , value ) : <EOL> if hasattr ( value , '<STR_LIT>' ) : <EOL> if self . to_field_name : <EOL> return value . serializable_value ( self . to_field_name ) <EOL> else : <EOL> return value . pk <EOL> return super ( ModelChoiceField , self ) . prepare_value ( value ) <EOL> def to_python ( self , value ) : <EOL> if value in EMPTY_VALUES : <EOL> return None <EOL> try : <EOL> key = self . to_field_name or '<STR_LIT>' <EOL> value = self . queryset . get ( ** { key : value } ) <EOL> except ( ValueError , self . queryset . model . DoesNotExist ) : <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT>' ] ) <EOL> return value <EOL> def validate ( self , value ) : <EOL> return Field . validate ( self , value ) <EOL> class ModelMultipleChoiceField ( ModelChoiceField ) : <EOL> """<STR_LIT>""" <EOL> widget = SelectMultiple <EOL> hidden_widget = MultipleHiddenInput <EOL> default_error_messages = { <EOL> '<STR_LIT:list>' : _ ( u'<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' <EOL> u'<STR_LIT>' ) , <EOL> '<STR_LIT>' : _ ( u'<STR_LIT>' ) <EOL> } <EOL> def __init__ ( self , queryset , cache_choices = False , required = True , <EOL> widget = None , label = None , initial = None , <EOL> help_text = None , * args , ** kwargs ) : <EOL> super ( ModelMultipleChoiceField , self ) . __init__ ( queryset , None , <EOL> cache_choices , required , widget , label , initial , help_text , <EOL> * args , ** kwargs ) <EOL> def clean ( self , value ) : <EOL> if self . required and not value : <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT>' ] ) <EOL> elif not self . required and not value : <EOL> return [ ] <EOL> if not isinstance ( value , ( list , tuple ) ) : <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT:list>' ] ) <EOL> key = self . to_field_name or '<STR_LIT>' <EOL> for pk in value : <EOL> try : <EOL> self . queryset . filter ( ** { key : pk } ) <EOL> except ValueError : <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT>' ] % pk ) <EOL> qs = self . queryset . filter ( ** { '<STR_LIT>' % key : value } ) <EOL> pks = set ( [ force_unicode ( getattr ( o , key ) ) for o in qs ] ) <EOL> for val in value : <EOL> if force_unicode ( val ) not in pks : <EOL> raise ValidationError ( self . error_messages [ '<STR_LIT>' ] % val ) <EOL> self . run_validators ( value ) <EOL> return qs <EOL> def prepare_value ( self , value ) : <EOL> if hasattr ( value , '<STR_LIT>' ) : <EOL> return [ super ( ModelMultipleChoiceField , self ) . prepare_value ( v ) for v in value ] <EOL> return super ( ModelMultipleChoiceField , self ) . prepare_value ( value ) </s>
