Hook for specifying the form Field instance for a given database Field
        instance.

        If kwargs are given, they're passed to the form Field's constructor.
514963
def formfield_for_dbfield(self, db_field, **kwargs):
        
        formfield = super().formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'image':
            formfield.widget = ImageRelatedFieldWidgetWrapper(
                ImageSelect(), db_field.rel, self.admin_site, can_add_related=True,
                can_change_related=True,
            )
        return formfield
143229
public static function set_form_fields($form, $instance = null)
	{
		Observer_Validation::set_fields($instance instanceof static ? $instance : get_called_class(), $form);
		$instance and $form->populate($instance, true);
	}
1233752
def initialize_form(self, instance, model, data=None, extra=None):
        
        model_fields = self.get_fields_from_model(model, self._filter_fields)

        forms = []
        if instance:
            for field_data in instance.list_fields():
                forms.append(
                    AdvancedFilterQueryForm._parse_query_dict(
                        field_data, model))

        formset = AFQFormSetNoExtra if not extra else AFQFormSet
        self.fields_formset = formset(
            data=data,
            initial=forms or None,
            model_fields=model_fields
        )
857953
def formfield_for_manytomany(self, db_field, request, **kwargs):
        '''
        
        '''
        db = kwargs.get('using')
        kwargs['queryset'] = kwargs.get('queryset', self.get_field_queryset(db, db_field, request))
        return super(AccessControlMixin, self).formfield_for_manytomany(db_field, request, **kwargs)
325926
def get_field_kwargs(self, field_name, model_field):
        
        kwargs = {}
        validator_kwarg = list(model_field.validators)

        # The following will only be used by ModelField classes.
        # Gets removed for everything else.
        kwargs['model_field'] = model_field

        if model_field.verbose_name and needs_label(model_field, field_name):
            kwargs['label'] = capfirst(model_field.verbose_name)

        if model_field.help_text:
            kwargs['help_text'] = model_field.help_text

        max_digits = getattr(model_field, 'max_digits', None)
        if max_digits is not None:
            kwargs['max_digits'] = max_digits

        decimal_places = getattr(model_field, 'decimal_places', None)
        if decimal_places is not None:
            kwargs['decimal_places'] = decimal_places

        if isinstance(model_field, models.TextField):
            kwargs['style'] = {'base_template': 'textarea.html'}

        if isinstance(model_field, models.AutoField) \
                or not model_field.editable:
            # If this field is read-only, then return early.
            # Further keyword arguments are not valid.
            kwargs['read_only'] = True
            return kwargs

        if model_field.has_default or model_field.blank or model_field.null:
            kwargs['required'] = False

        if model_field.null and not isinstance(model_field,
                                               models.NullBooleanField):
            kwargs['allow_null'] = True

        if model_field.blank and (
            isinstance(model_field, models.CharField) or
            isinstance(model_field, models.TextField) or
            isinstance(model_field, columns.Text)
        ):
            kwargs['allow_blank'] = True

        if isinstance(model_field, models.FilePathField):
            kwargs['path'] = model_field.path

            if model_field.match is not None:
                kwargs['match'] = model_field.match

            if model_field.recursive is not False:
                kwargs['recursive'] = model_field.recursive

            if model_field.allow_files is not True:
                kwargs['allow_files'] = model_field.allow_files

            if model_field.allow_folders is not False:
                kwargs['allow_folders'] = model_field.allow_folders

        if model_field.choices:
            # If this model field contains choices, then return early.
            # Further keyword arguments are not valid.
            kwargs['choices'] = model_field.choices
            return kwargs

        # Our decimal validation is handled in the field code,
        # not validator code.
        # (In Django 1.9+ this differs from previous style)
        if isinstance(model_field, models.DecimalField) and DecimalValidator:
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, DecimalValidator)
            ]

        # Ensure that max_length is passed explicitly as a keyword arg,
        # rather than as a validator.
        max_length = getattr(model_field, 'max_length', None)
        if max_length is not None and (
                    isinstance(model_field, models.CharField) or
                    isinstance(model_field, models.TextField)):
            kwargs['max_length'] = max_length
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.MaxLengthValidator)
            ]

        # Ensure that min_length is passed explicitly as a keyword arg,
        # rather than as a validator.
        min_length = next((
            validator.limit_value for validator in validator_kwarg
            if isinstance(validator, validators.MinLengthValidator)
        ), None)
        if min_length is not None and isinstance(model_field,
                                                 models.CharField):
            kwargs['min_length'] = min_length
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.MinLengthValidator)
            ]

        # Ensure that max_value is passed explicitly as a keyword arg,
        # rather than as a validator.
        max_value = next((
            validator.limit_value for validator in validator_kwarg
            if isinstance(validator, validators.MaxValueValidator)
        ), None)
        if max_value is not None and isinstance(model_field,
                                                NUMERIC_FIELD_TYPES):
            kwargs['max_value'] = max_value
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.MaxValueValidator)
            ]

        # Ensure that max_value is passed explicitly as a keyword arg,
        # rather than as a validator.
        min_value = next((
            validator.limit_value for validator in validator_kwarg
            if isinstance(validator, validators.MinValueValidator)
        ), None)
        if min_value is not None and isinstance(model_field,
                                                NUMERIC_FIELD_TYPES):
            kwargs['min_value'] = min_value
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.MinValueValidator)
            ]

        # URLField does not need to include the URLValidator argument,
        # as it is explicitly added in.
        if isinstance(model_field, models.URLField):
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.URLValidator)
            ]

        # EmailField does not need to include the validate_email argument,
        # as it is explicitly added in.
        if isinstance(model_field, models.EmailField):
            validator_kwarg = [
                validator for validator in validator_kwarg
                if validator is not validators.validate_email
            ]

        # SlugField do not need to include the 'validate_slug' argument,
        if isinstance(model_field, models.SlugField):
            validator_kwarg = [
                validator for validator in validator_kwarg
                if validator is not validators.validate_slug
            ]

        # IPAddressField do not need to include the 'validate_ipv46_address'
        # argument,
        if isinstance(model_field, models.GenericIPAddressField):
            validator_kwarg = [
                validator for validator in validator_kwarg
                if validator is not validators.validate_ipv46_address
            ]

        if getattr(model_field, 'unique', False):
            warnings.warn(
                'UniqueValidator is currently not supported '
                'in DjangoCassandraSerializer'
            )

        if validator_kwarg:
            kwargs['validators'] = validator_kwarg

        return kwargs
997326
private static DatabaseFieldConfig buildConfig(DatabaseField databaseField, String tableName, Field field)
			throws Exception {
		InvocationHandler proxy = Proxy.getInvocationHandler(databaseField);
		if (proxy.getClass() != annotationFactoryClazz) {
			return null;
		}
		// this should be an array of AnnotationMember objects
		Object elementsObject = elementsField.get(proxy);
		if (elementsObject == null) {
			return null;
		}
		DatabaseFieldConfig config = new DatabaseFieldConfig(field.getName());
		Object[] objs = (Object[]) elementsObject;
		for (int i = 0; i < configFieldNums.length; i++) {
			Object value = valueField.get(objs[i]);
			if (value != null) {
				assignConfigField(configFieldNums[i], config, field, value);
			}
		}
		return config;
	}
1078837
def formfield_for_dbfield(self, db_field, **kwargs):
        
        if isinstance(db_field, models.ForeignKey) and db_field.name in self.related_search_fields:
            help_text = self.get_help_text(db_field.name, db_field.remote_field.model._meta.object_name)
            if kwargs.get('help_text'):
                help_text = six.u('%s %s' % (kwargs['help_text'], help_text))
            kwargs['widget'] = ForeignKeySearchInput(db_field.remote_field, self.related_search_fields[db_field.name])
            kwargs['help_text'] = help_text
        return super(ForeignKeyAutocompleteAdminMixin, self).formfield_for_dbfield(db_field, **kwargs)
1215897
def widget_kwargs_for_field(self, field_name):
        
        if self._meta.widgets:
            return self._meta.widgets.get(field_name, {})
        return {}
260524
def get_form_kwargs(self, key):
        
        kwargs = {
            'initial': self.get_initial(key),
            'prefix': self.get_prefix(key),
        }

        if self.request.method in ('POST', 'PUT'):
            kwargs.update({
                'data': self.request.POST,
                'files': self.request.FILES,
            })
        return kwargs
268164
def _set_fields(self, fields):
        """"""
        for f in fields:
            if hasattr(self, f):
                setattr(self, f, fields[f])
            else:
                raise TypeError("'{arg}' is an invalid argument for {instance_type}".format(arg=f, instance_type=self.__class__.__name__))
97785
def _ipopo_setup_field_callback(cls, context):
    # type: (type, FactoryContext) -> None
    
    assert inspect.isclass(cls)
    assert isinstance(context, FactoryContext)

    if context.field_callbacks is not None:
        callbacks = context.field_callbacks.copy()
    else:
        callbacks = {}

    functions = inspect.getmembers(cls, inspect.isroutine)
    for name, func in functions:
        if not hasattr(func, constants.IPOPO_METHOD_FIELD_CALLBACKS):
            # No attribute, get the next member
            continue

        method_callbacks = getattr(func, constants.IPOPO_METHOD_FIELD_CALLBACKS)
        if not isinstance(method_callbacks, list):
            # Invalid content
            _logger.warning(
                "Invalid attribute %s in %s",
                constants.IPOPO_METHOD_FIELD_CALLBACKS,
                name,
            )
            continue

        # Keeping it allows inheritance : by removing it, only the first
        # child will see the attribute -> Don't remove it

        # Store the call backs
        for kind, field, if_valid in method_callbacks:
            fields_cbs = callbacks.setdefault(field, {})

            if kind in fields_cbs and not is_from_parent(
                cls, fields_cbs[kind][0].__name__
            ):
                _logger.warning(
                    "Redefining the callback %s in '%s'. "
                    "Previous callback : '%s' (%s). "
                    "New callback : %s",
                    kind,
                    name,
                    fields_cbs[kind][0].__name__,
                    fields_cbs[kind][0],
                    func,
                )

            fields_cbs[kind] = (func, if_valid)

    # Update the factory context
    context.field_callbacks.clear()
    context.field_callbacks.update(callbacks)
814064
def get_form_kwargs(self):
        
        kwargs = {"user": self.request.user, "initial": self.get_initial()}
        if self.request.method in ["POST", "PUT"]:
            kwargs.update({
                "data": self.request.POST,
                "files": self.request.FILES,
            })
        return kwargs
907048
def _bind_field(self, field_name, field_obj):
        
        try:
            if field_name in self.load_only:
                field_obj.load_only = True
            if field_name in self.dump_only:
                field_obj.dump_only = True
            field_obj._bind_to_schema(field_name, self)
            self.on_bind_field(field_name, field_obj)
        except TypeError:
            # field declared as a class, not an instance
            if (isinstance(field_obj, type) and
                    issubclass(field_obj, base.FieldABC)):
                msg = ('Field for "{}" must be declared as a '
                       'Field instance, not a class. '
                       'Did you mean "fields.{}()"?'
                       .format(field_name, field_obj.__name__))
                raise TypeError(msg)
528768
def process_form(self, instance, field, form, empty_marker=None,
                     emptyReturnsMarker=False):
        
        fieldName = field.getName()
        if fieldName + "_uid" in form:
            uid = form.get(fieldName + "_uid", '')
            if field.multiValued and\
                    (isinstance(uid, str) or isinstance(uid, unicode)):
                uid = uid.split(",")
        elif fieldName in form:
            uid = form.get(fieldName, '')
            if field.multiValued and\
                    (isinstance(uid, str) or isinstance(uid, unicode)):
                uid = uid.split(",")
        else:
            uid = None
        return uid, {}
87394
def create_values(self, base_model=models.Model, base_manager=models.Manager):
        

        _builder = self

        class CustomContentTypeFieldValueManager(base_manager):
            def create(self, **kwargs):
                """
                Subclass create in order to be able to use "value" in kwargs
                instead of using "value_%s" passing also type directly
                """
                if 'value' in kwargs:
                    value = kwargs.pop('value')
                    created_object = super(CustomContentTypeFieldValueManager, self).create(**kwargs)
                    created_object.value = value
                    return created_object
                else:
                    return super(CustomContentTypeFieldValueManager, self).create(**kwargs)

        @python_2_unicode_compatible
        class CustomContentTypeFieldValue(base_model):
            custom_field = models.ForeignKey('.'.join(_builder.fields_model),
                                             verbose_name=_('custom field'),
                                             related_name='+')
            content_type = models.ForeignKey(ContentType, editable=False,
                                             verbose_name=_('content type'),
                                             limit_choices_to=_builder.content_types_query)
            object_id = models.PositiveIntegerField(_('object id'), db_index=True)
            content_object = GenericForeignKey('content_type', 'object_id')

            value_text = models.TextField(blank=True, null=True)
            value_integer = models.IntegerField(blank=True, null=True)
            value_float = models.FloatField(blank=True, null=True)
            value_time = models.TimeField(blank=True, null=True)
            value_date = models.DateField(blank=True, null=True)
            value_datetime = models.DateTimeField(blank=True, null=True)
            value_boolean = models.NullBooleanField(blank=True)

            objects = CustomContentTypeFieldValueManager()

            def _get_value(self):
                return getattr(self, 'value_%s' % self.custom_field.data_type)

            def _set_value(self, new_value):
                setattr(self, 'value_%s' % self.custom_field.data_type, new_value)

            value = property(_get_value, _set_value)

            class Meta:
                unique_together = ('custom_field', 'content_type', 'object_id')
                verbose_name = _('custom field value')
                verbose_name_plural = _('custom field values')
                abstract = True

            def save(self, *args, **kwargs):
                # save content type as user shouldn't be able to change it
                self.content_type = self.custom_field.content_type
                super(CustomContentTypeFieldValue, self).save(*args, **kwargs)

            def validate_unique(self, exclude=None):
                qs = self.__class__._default_manager.filter(
                    custom_field=self.custom_field,
                    content_type=self.custom_field.content_type,
                    object_id=self.object_id,
                )
                if not self._state.adding and self.pk is not None:
                    qs = qs.exclude(pk=self.pk)
                if qs.exists():
                    raise ValidationError({ NON_FIELD_ERRORS: (_('A value for this custom field already exists'),) })

            def __str__(self):
                return "%s: %s" % (self.custom_field.name, self.value)

        return CustomContentTypeFieldValue
576131
function constructor(attributes, options) {
      var hooks = []
        , local = {};

      options = options || {};

      //
      // Set the database name and/or urlRoot if provided in the options.
      //
      if (options.database) this.database = options.database;
      if (options.urlRoot) this.urlRoot = options.urlRoot;

      //
      // Copy attributes to a new object and provide a MongoDB OfbjectID.
      //
      attributes = attributes || {};
      for (var key in attributes) local[key] = attributes[key];

      //
      // If the provided `_id` is an ObjectID assume the model is stored.
      // If it is not an ObjectID, remove it from the provided data.
      // MongoDB will provide an ObjectID by default.
      //
      if ('_id' in local) try {
        local._id = new ObjectID(local._id);
      } catch (error) { delete local._id; }

      //
      // Define restricted non-enumerated properties.
      //
      predefine(this, fossa);

      //
      // Check for presence of before/after hooks and setup.
      //
      if (this.before) hooks.push('before');
      if (this.after) hooks.push('after');
      this.setup(hooks);

      //
      // Call original Backbone Model constructor.
      //
      backbone.Model.call(this, local, options);
    }
444469
public function definition() {
        global $PAGE;
        $mform = $this->_form;

        $field = $this->_customdata['field'];
        if (!($field && $field instanceof field_controller)) {
            throw new \coding_exception('Field must be passed in customdata');
        }
        $handler = $field->get_handler();

        $mform->addElement('header', '_commonsettings', get_string('commonsettings', 'core_customfield'));

        $mform->addElement('text', 'name', get_string('fieldname', 'core_customfield'), 'size="50"');
        $mform->addRule('name', null, 'required', null, 'client');
        $mform->setType('name', PARAM_TEXT);

        // Accepted values for 'shortname' would follow [a-z0-9_] pattern,
        // but we are accepting any PARAM_TEXT value here,
        // and checking [a-zA-Z0-9_] pattern in validation() function to throw an error when needed.
        $mform->addElement('text', 'shortname', get_string('fieldshortname', 'core_customfield'), 'size=20');
        $mform->addHelpButton('shortname', 'shortname', 'core_customfield');
        $mform->addRule('shortname', null, 'required', null, 'client');
        $mform->setType('shortname', PARAM_TEXT);

        $desceditoroptions = $handler->get_description_text_options();
        $mform->addElement('editor', 'description_editor', get_string('description', 'core_customfield'), null, $desceditoroptions);
        $mform->addHelpButton('description_editor', 'description', 'core_customfield');

        // If field is required.
        $mform->addElement('selectyesno', 'configdata[required]', get_string('isfieldrequired', 'core_customfield'));
        $mform->addHelpButton('configdata[required]', 'isfieldrequired', 'core_customfield');
        $mform->setType('configdata[required]', PARAM_BOOL);

        // If field data is unique.
        $mform->addElement('selectyesno', 'configdata[uniquevalues]', get_string('isdataunique', 'core_customfield'));
        $mform->addHelpButton('configdata[uniquevalues]', 'isdataunique', 'core_customfield');
        $mform->setType('configdata[uniquevalues]', PARAM_BOOL);

        // Field specific settings from field type.
        $field->config_form_definition($mform);

        // Handler/component settings.
        $handler->config_form_definition($mform);

        // We add hidden fields.
        $mform->addElement('hidden', 'categoryid');
        $mform->setType('categoryid', PARAM_INT);

        $mform->addElement('hidden', 'type');
        $mform->setType('type', PARAM_COMPONENT);

        $mform->addElement('hidden', 'id');
        $mform->setType('id', PARAM_INT);

        $this->add_action_buttons(true);
    }