def __new__(cls, *args, **kwargs): new_class = super().__new__(cls, **kwargs) config = getattr(cls, 'Meta', None) model_opts = ModelFormOptions(getattr(config.model, '_meta', None)) model_opts.exclude = getattr(config, 'exclude', tuple()) fields = fields_for_model( model=model_opts.model, fields=None, exclude=model_opts.exclude, widgets=None, formfield_callback=None, localized_fields=model_opts.localized_fields, labels=model_opts.labels, help_texts=model_opts.help_texts, error_messages=model_opts.error_messages, field_classes=model_opts.field_classes, apply_limit_choices_to=False, ) # AutoField has to be added manually # Do not add AutoFields right now # if config.model._meta.auto_field and config.model._meta.auto_field.attname not in model_opts.exclude: # fields[config.model._meta.auto_field.attname] = IntegerField() fields.update(new_class.declared_fields) # Remove None value keys fields = {k: v for k, v in fields.items() if v is not None} new_class.base_fields = fields new_class.declared_fields = fields return new_class
def get_form_class(self): if self.home_team: side = "home" else: side = "away" queryset = TeamMembership.objects.filter(team=self.team, active=True) if self.team.tournament.structure == "I": queryset = queryset.filter(char_code__isnull=False) player = forms.ModelChoiceField(queryset=queryset, label='Player') race = forms.ChoiceField(label='Race', choices=[('', '---------')] + list(RACES)) namespace = { 'base_fields': { side + '_player': player, side + '_race': race }, '_meta': ModelFormOptions({ 'model': Game, 'fields': (side + '_player', side + '_race') }) } form = type('SubmitLineupForm', (BaseModelForm, ), namespace) return inlineformset_factory(Match, Game, extra=0, can_delete=False, form=form)
def __new__(cls, name, bases, attrs): formfield_callback = attrs.pop('formfield_callback', lambda f: f.formfield()) try: parents = [b for b in bases if issubclass(b, ModelForm)] except NameError: # We are defining ModelForm itself. parents = None declared_fields = get_declared_fields(bases, attrs, False) new_class = super(ModelFormMetaclass, cls).__new__(cls, name, bases, attrs) if not parents: return new_class if 'media' not in attrs: new_class.media = media_property(new_class) opts = new_class._meta = ModelFormOptions( getattr(new_class, 'Meta', None)) if opts.model: # If a model is defined, extract form fields from it. fields = fields_for_model(opts.model, opts.fields, opts.exclude, formfield_callback) # Override default model fields with any custom declared ones # (plus, include all the other declared fields). fields.update(declared_fields) else: fields = declared_fields new_class.declared_fields = declared_fields new_class.base_fields = fields return new_class
def __init__(self, *args, **kwargs): self.instance = kwargs.pop('instance', PackMember()) super(PackMemberForm, self).__init__(*args, **kwargs) self.fields['member'] = ProductionField( initial=self.instance.member_id, # supertype='production', # add this if we require pack members to be productions (not music or gfx) ) self._meta = ModelFormOptions() # required by BaseModelFormSet.add_fields. eww.
def __init__(self, *args, **kwargs): self.instance = kwargs.pop('instance', SoundtrackLink()) super(SoundtrackLinkForm, self).__init__(*args, **kwargs) self.fields['soundtrack'] = ProductionField( initial=self.instance.soundtrack_id, supertype='music', types_to_set=[ProductionType.objects.get(internal_name='music')], ) self._meta = ModelFormOptions() # required by BaseModelFormSet.add_fields. eww.
def get_form_class(self, **kwargs): """ Returns the form class to use in this view. """ if 'fields' in kwargs: fields = kwargs.pop('fields') else: fields = self.get_fields() exclude = [] # TODO: Need to remove readonly fields from form, but include them when returning by get_ng_model # if self.request.method == 'POST': # exclude = self.get_readonly_fields(); if self.form_class: if fields or len(exclude) > 0: # TODO make sure it is saving all form_class definitions!!!!! if fields == '__all__': fields = ModelFormOptions(self.form_class).fields form_class = _model_forms.modelform_factory( self.model, form=self.form_class, fields=fields, exclude=exclude) else: form_class = self.form_class else: model = None if self.model is not None: # If a model has been explicitly provided, use it model = self.model elif hasattr(self, 'object') and self.object is not None: # If this view is operating on a single object, use # the class of that object model = self.object.__class__ else: # Try to get a queryset and extract the model class # from that model = self.get_queryset().model if fields is None and model is None: raise ImproperlyConfigured( "Using ModelFormMixin (base class of %s) without " "the 'fields' attribute is prohibited." % self.__class__.__name__) form_class = _model_forms.modelform_factory( model, form=ModelForm, fields=(fields if fields else self.fields), exclude=exclude) for field in self.get_readonly_fields(): if form_class.base_fields.get(field, False): form_class.base_fields[field].required = False form_class.base_fields[field].is_disabled = True return form_class
def __new__(mcs, name, bases, attrs): new_class = super(SearchFormMetaclass, mcs).__new__(mcs, name, bases, attrs) new_class.opts = new_class._meta = ModelFormOptions( getattr(new_class, 'Meta', None)) # here the purpose for the meta class - to assign model to the widget new_class.base_fields['q'] = forms.CharField(widget=SearchInput( model=new_class.opts.model)) return new_class
def __new__(mcs, name, bases, attrs): declared_fields = get_declared_fields(bases, attrs, False) new_class = super(ModelFormMetaclass, mcs).__new__(mcs, name, bases, attrs) if bases == (BaseEGModelForm, ): return new_class if 'media' not in attrs: new_class.media = media_property(new_class) opts = new_class._meta = ModelFormOptions( getattr(new_class, 'Meta', None)) if opts.model: # If a model is defined, extract form fields from it. if opts.fields is None and opts.exclude is None: raise ImproperlyConfigured( "Creating a ModelForm without either the 'fields' attribute " "or the 'exclude' attribute is prohibited; form %s " "needs updating." % name) if opts.fields == ALL_FIELDS: # Sentinel for fields_for_model to indicate "get the list of # fields from the model" opts.fields = None fields = fields_for_model(opts.model, opts.fields, opts.exclude, opts.widgets, opts.localized_fields, opts.labels, opts.help_texts, opts.error_messages) # make sure opts.fields doesn't specify an invalid field none_model_fields = [k for k, v in six.iteritems(fields) if not v] missing_fields = (set(none_model_fields) - set(declared_fields.keys())) if missing_fields: message = 'Unknown field(s) (%s) specified for %s' message = message % (', '.join(missing_fields), opts.model.__name__) raise FieldError(message) # Override default model fields with any custom declared ones # (plus, include all the other declared fields). fields.update(declared_fields) else: fields = declared_fields new_class.base_fields = fields new_class.declared_fields = declared_fields return new_class
def __new__(cls, name, bases, attrs): fields = [(field_name, attrs.pop(field_name)) for field_name, obj in attrs.items() if isinstance(obj, Field)] fields.sort( lambda x, y: cmp(x[1].creation_counter, y[1].creation_counter)) # If this class is subclassing another Form, add that Form's fields. # Note that we loop over the bases in *reverse*. This is necessary in # order to preserve the correct order of fields. for base in bases[::-1]: if hasattr(base, 'base_fields'): fields = base.base_fields.items() + fields attrs['base_fields'] = SortedDictFromList(fields) # rest of this method is taken from actual django # source for ModelFormMetaclass class formfield_callback = attrs.pop('formfield_callback', lambda f: f.formfield()) try: parents = [b for b in bases if issubclass(b, BaseModelForm)] except NameError: # We are defining ModelForm itself. parents = None declared_fields = get_declared_fields(bases, attrs, False) new_class = super(SmartModelFormMetaclass, cls).__new__(cls, name, bases, attrs) if not parents: return new_class if 'media' not in attrs: new_class.media = media_property(new_class) opts = new_class._meta = ModelFormOptions( getattr(new_class, 'Meta', None)) if opts.model: # If a model is defined, extract form fields from it. fields = fields_for_model(opts.model, opts.fields, opts.exclude, formfield_callback) # Override default model fields with any custom declared ones # (plus, include all the other declared fields). fields.update(declared_fields) else: fields = declared_fields new_class.declared_fields = declared_fields new_class.base_fields = fields return new_class
def __init__(self, *args, **kwargs): parent_form_fields = None for cls in self.__class__.__bases__: if hasattr(cls, 'Meta'): opts = ModelFormOptions(getattr(cls, 'Meta')) parent_form_fields = opts.fields if parent_form_fields: for field in self.base_fields.keys(): if not field in parent_form_fields: del self.base_fields[field] self._base_fields = self.base_fields.copy() for cls in self.model_form_classes: if issubclass(cls, ModelFormSet): raise ImproperlyConfigured('Child class %s can not be subclass of ModelFormSet' % cls) name = cls.__name__.lower() self._model_forms[name] = cls(*args, **kwargs) form = self._model_forms[name] self.base_fields.update(form.fields) super(ModelFormSet, self).__init__(*args, **kwargs)
def __new__(cls, name, bases, attrs): """ Django 1.3 fix, that removes all Meta.fields and Meta.exclude fieldnames that are in the translatable model. This ensures that the superclass' init method doesnt throw a validation error """ fields = [] exclude = [] fieldsets = [] if "Meta" in attrs: meta = attrs["Meta"] if getattr(meta, "fieldsets", False): fieldsets = meta.fieldsets meta.fieldsets = [] if getattr(meta, "fields", False): fields = meta.fields meta.fields = [] if getattr(meta, "exclude", False): exclude = meta.exclude meta.exclude = [] # End 1.3 fix super_new = super(TranslatableModelFormMetaclass, cls).__new__ formfield_callback = attrs.pop('formfield_callback', None) declared_fields = get_declared_fields(bases, attrs, False) new_class = super_new(cls, name, bases, attrs) # Start 1.3 fix if fields: new_class.Meta.fields = fields if exclude: new_class.Meta.exclude = exclude if fieldsets: new_class.Meta.fieldsets = fieldsets # End 1.3 fix if not getattr(new_class, "Meta", None): class Meta: exclude = ['language_code'] new_class.Meta = Meta elif not getattr(new_class.Meta, 'exclude', None): new_class.Meta.exclude = ['language_code'] elif getattr(new_class.Meta, 'exclude', False): if 'language_code' not in new_class.Meta.exclude: new_class.Meta.exclude.append("language_code") if 'Media' not in attrs: new_class.media = media_property(new_class) opts = new_class._meta = ModelFormOptions(getattr(new_class, 'Meta', attrs.get('Meta', None))) if opts.model: # bail out if a wrong model uses this form class if not issubclass(opts.model, TranslatableModel): raise TypeError( "Only TranslatableModel subclasses may use TranslatableModelForm" ) mopts = opts.model._meta shared_fields = mopts.get_all_field_names() # split exclude and include fieldnames into shared and translated sfieldnames = [field for field in opts.fields or [] if field in shared_fields] tfieldnames = [field for field in opts.fields or [] if field not in shared_fields] sexclude = [field for field in opts.exclude or [] if field in shared_fields] texclude = [field for field in opts.exclude or [] if field not in shared_fields] # required by fields_for_model if not sfieldnames : sfieldnames = None if not fields else [] if not tfieldnames: tfieldnames = None if not fields else [] # If a model is defined, extract form fields from it. sfields = fields_for_model(opts.model, sfieldnames, sexclude, opts.widgets, formfield_callback) tfields = fields_for_model(mopts.translations_model, tfieldnames, texclude, opts.widgets, formfield_callback) fields = sfields fields.update(tfields) # make sure opts.fields doesn't specify an invalid field none_model_fields = [k for k, v in fields.iteritems() if not v] missing_fields = set(none_model_fields) - \ set(declared_fields.keys()) if missing_fields: message = 'Unknown field(s) (%s) specified for %s' message = message % (', '.join(missing_fields), opts.model.__name__) raise FieldError(message) # Override default model fields with any custom declared ones # (plus, include all the other declared fields). fields.update(declared_fields) if new_class._meta.exclude: new_class._meta.exclude = list(new_class._meta.exclude) else: new_class._meta.exclude = [] for field in (mopts.translations_accessor, 'master'): if not field in new_class._meta.exclude: new_class._meta.exclude.append(field) else: fields = declared_fields new_class.declared_fields = declared_fields new_class.base_fields = fields # always exclude the FKs return new_class
def __new__(cls, name, bases, attrs): formfield_callback = attrs.pop('formfield_callback', None) try: parents = [b for b in bases if issubclass(b, BaseModelForm)] # for Django<=1.6, fix bug in forms.models: ^^^^^^^^^^^^^ except NameError: # We are defining ModelForm itself. parents = None declared_fields = get_declared_fields(bases, attrs, False) new_class = super(PatchedModelFormMetaclass, cls).__new__(cls, name, bases, attrs) if not parents: return new_class if 'media' not in attrs: new_class.media = media_property(new_class) opts = new_class._meta = ModelFormOptions( getattr(new_class, 'Meta', None)) # We check if a string was passed to `fields` or `exclude`, # which is likely to be a mistake where the user typed ('foo') instead # of ('foo',) for opt in ['fields', 'exclude', 'localized_fields']: value = getattr(opts, opt) if isinstance(value, six.string_types) and value != ALL_FIELDS: msg = ("%(model)s.Meta.%(opt)s cannot be a string. " "Did you mean to type: ('%(value)s',)?" % { 'model': new_class.__name__, 'opt': opt, 'value': value, }) raise TypeError(msg) if opts.model: # If a model is defined, extract form fields from it. if opts.fields is None and opts.exclude is None: # This should be some kind of assertion error once deprecation # cycle is complete. warnings.warn( "Creating a ModelForm without either the 'fields' attribute " "or the 'exclude' attribute is deprecated - form %s " "needs updating" % name, PendingDeprecationWarning, stacklevel=2) if opts.fields == ALL_FIELDS: # sentinel for fields_for_model to indicate "get the list of # fields from the model" opts.fields = None fields = fields_for_model(opts.model, opts.fields, opts.exclude, opts.widgets, formfield_callback, opts.localized_fields, opts.labels, opts.help_texts, opts.error_messages) # make sure opts.fields doesn't specify an invalid field none_model_fields = [k for k, v in six.iteritems(fields) if not v] missing_fields = set(none_model_fields) - \ set(declared_fields.keys()) if missing_fields: message = 'Unknown field(s) (%s) specified for %s' message = message % (', '.join(missing_fields), opts.model.__name__) raise FieldError(message) # Override default model fields with any custom declared ones # (plus, include all the other declared fields). fields.update(declared_fields) else: fields = declared_fields new_class.declared_fields = declared_fields new_class.base_fields = fields return new_class