Either return the formset class that was provided as argument to the
        __init__ method, or build one based on the ``parent_model`` and
        ``model`` attributes.
483733
def get_formset_class(self, form, name):
        
        if self.formset_class is not None:
            return self.formset_class
        formset_class = inlineformset_factory(
            self.get_parent_model(form, name),
            self.get_model(form, name),
            **self.formset_factory_kwargs)
        return formset_class
366589
def augment_init_method(cls):
    

    orig_init = cls.__init__

    def new_init(self, *args, **kwargs):
        super(CustomGenerator, self).__init__()  # TODO: does this behave correctly with longer inheritance chains?

        orig_init(self, *args, **kwargs)

        self.orig_args = args
        self.orig_kwargs = kwargs

        self.ns_gen_templates = TohuNamespace()
        self.ns_gen_templates.update_from_dict(self.__class__.__dict__)
        self.ns_gen_templates.update_from_dict(self.__dict__)
        self.ns_gen_templates.set_owner(self.__class__)
        self._mark_field_generator_templates()

        self.ns_gens = self.ns_gen_templates.spawn()
        self.ns_gens.set_owner(self)

        self._update_namespace_with_field_generators()
        self._set_field_names()
        self._set_tohu_items_name()
        self._set_tohu_items_cls()

    cls.__init__ = new_init
1254628
def get_form(self, form_class=None):
        """"""
        form = super().get_form(form_class)

        if not getattr(form, 'helper', None):
            form.helper = FormHelper()
            form.helper.form_tag = False
        else:
            form.helper.form_tag = False
        return form
1374993
def get_fieldsets(self, request, obj=None):
        '''  '''
        # If subclass declares fieldsets, this is respected
        if (hasattr(self, 'declared_fieldset') and self.declared_fieldsets) \
           or not self.base_fieldsets:
            return super(PolymorphicChildModelAdmin, self).get_fieldsets(request, obj)

        other_fields = self.get_subclass_fields(request, obj)

        if other_fields:
            return (
                (self.extra_fieldset_title, {'fields': other_fields}),
            ) + self.base_fieldsets
        else:
            return self.base_fieldsets
1057926
def model_set(method_name):
    

    def model_set(value, context, **_params):
        method = getattr(context["model"], method_name)
        return _set(method, context["key"], value, (), {})

    return model_set
301798
def get_parent_object(self, parent_queryset=None):
        
        if self._parent_object_cache is not None:
            return self._parent_object_cache

        if parent_queryset is None:
            parent_queryset = self.get_parent_queryset()

        if self.parent_model is None:
            raise ImproperlyConfigured(
                "'%s' must define 'parent_model'" % self.__class__.__name__
            )

        if self.parent_lookup_field is None:
            raise ImproperlyConfigured(
                "'%s' must define 'parent_lookup_field'" % self.__class__.__name__  # noqa
            )

        lookup_url_kwarg = '_'.join([
            self.parent_model_name or self.parent_model._meta.model_name,
            self.parent_lookup_field
        ])

        lookup = self.kwargs.get(lookup_url_kwarg, None)

        if lookup is not None:
            filter_kwargs = {self.parent_lookup_field: lookup}

        else:
            raise ImproperlyConfigured(
                'Expected view %s to be called with a URL keyword argument '
                'named "%s". Fix your URL conf, or set the '
                '`parent_lookup_field` attribute on the view correctly.' %
                (self.__class__.__name__, lookup_url_kwarg)
            )

        obj = get_object_or_404(parent_queryset, **filter_kwargs)

        self.check_parent_object_permissions(self.request, obj)
        self._parent_object_cache = obj

        return obj
261967
def to_set_field(cls):
    
    class SetConverter(object):

        def __init__(self, cls):
            self._cls = cls

        @property
        def cls(self):
            return resolve_class(self._cls)

        def __call__(self, values):
            values = values or set()
            args = {to_model(self.cls, value) for value in values}
            return TypedSet(cls=self.cls, args=args)

    return SetConverter(cls)
202158
def get_form_instance(self, request, data=None, instance=None):
        
        defaults = {}
        if self.form:
            defaults['form'] = self.form
        if self.fields:
            defaults['fields'] = self.fields
        return modelform_factory(self.model, **defaults)(data=data, instance=instance)
600134
def create(cls):
        

        class NewPopupCreateView(PopupCreateView, cls.parent_class):
            model = cls.model
            form_class = cls.form_class
            popup_name = cls.get_class_verbose_name()
            template_name = cls.get_template_name_create()
            permission_required = cls.get_permission_required('create')

            def get_context_data(self, **kwargs):
                kwargs.update(cls.context_for_all)
                kwargs.update(cls.context_for_create)
                return super(NewPopupCreateView, self).get_context_data(**kwargs)

        return NewPopupCreateView
400504
def get_forms(self):
        
        forms = {}
        objects = self.get_objects()
        initial = self.get_initial()
        form_kwargs = self.get_form_kwargs()
        for key, form_class in six.iteritems(self.form_classes):
            forms[key] = form_class(instance=objects[key], initial=initial[key], **form_kwargs[key])
        return forms
483667
def _init_fields(self):
        
        fields = {}
        forms = {}
        sets = {}

        for name in dir(self):
            if name.startswith('_'):
                continue
            field = getattr(self, name)
            is_field = isinstance(field, Field)
            is_form = isinstance(field, Form) or (
                inspect.isclass(field) and issubclass(field, Form))
            is_set = isinstance(field, FormSet)

            if is_field:
                field = copy(field)
                field.name = self._prefix + name
                field.form = self
                if field.prepare is None:
                    field.prepare = getattr(self, 'prepare_' + name, None)
                if field.clean is None:
                    field.clean = getattr(self, 'clean_' + name, None)
                fields[name] = field
                setattr(self, name, field)
            elif is_form:
                forms[name] = field
            elif is_set:
                field._name = self._prefix + name  # REALLY IMPORTANT
                sets[name] = field

        self._fields = fields
        self._forms = forms
        self._sets = sets
776926
protected static function initAttributeSet()
    {
        $className = get_called_class();
        
        if (!ModelAttributes::attributesSetFor($className)) {
            ModelAttributes::setClassAttributes(
                $className,
                static::attributeSet()
            );
        }
    }
531999
def patch_constructor(model):
    
    old_init = model.__init__

    def new_init(self, *args, **kwargs):
        self._mt_init = True
        populate_translation_fields(self.__class__, kwargs)
        for key, val in list(kwargs.items()):
            new_key = rewrite_lookup_key(model, key)
            # Old key is intentionally left in case old_init wants to play with it
            kwargs.setdefault(new_key, val)
        old_init(self, *args, **kwargs)
    model.__init__ = new_init
426413
def get_factory_kwargs(self):
        
        kwargs = {}
        kwargs.update({
            'can_delete': self.can_delete,
            'extra': self.extra,
            'exclude': self.exclude,
            'fields': self.fields,
            'formfield_callback': self.formfield_callback,
            'fk_name': self.fk_name,
        })
        if self.formset_class:
            kwargs['formset'] = self.formset_class

        if self.child_form:
            kwargs['form'] = self.child_form
        return kwargs
637498
def init_form_view(self, view, opts):
        
        name = opts.get("name", opts.get("form"))
        if isinstance(name, Form):
            return

        template = opts.get("template", getattr(view, "template", None))
        if not template:
            if not name:
                raise NoFormError("No form name specified in the form action and no template")
            return

        try:
            as_ = opts.get("var_name", getattr(self.form, "as_", "form"))
            form_class = create_from_template(current_app, template, var_name=as_)
        except NoFormError:
            if not name:
                raise
            return

        if not name:
            name = view.name

        self.forms[name] = form_class
        self.form_created_from_view_signal.send(self, view=view, form_class=form_class)
        return form_class
1322200
def smartformset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
                         can_delete=False, min_num=None, max_num=None, validate_min=False, validate_max=False):
    """"""
    if max_num is None:
        max_num = DEFAULT_MAX_NUM
    # hard limit on forms instantiated, to prevent memory-exhaustion attacks
    # limit is simply max_num + DEFAULT_MAX_NUM (which is 2*DEFAULT_MAX_NUM
    # if max_num is None in the first place)
    absolute_max = max_num + DEFAULT_MAX_NUM
    if min_num is None:
        min_num = 0

    attrs = {'form': form, 'extra': extra,
             'can_order': can_order, 'can_delete': can_delete, 'min_num': min_num,
             'max_num': max_num, 'absolute_max': absolute_max, 'validate_min': validate_min,
             'validate_max': validate_max}
    return type(form.__name__ + str('FormSet'), (formset,), attrs)
1069505
def get_formfield(model, field):
    
    class_field = model._meta.get_field(field)

    if hasattr(class_field, "field"):
        formfield = class_field.field.formfield()
    else:
        formfield = class_field.formfield()
    
    # Otherwise the formfield contain the reverse relation
    if isinstance(formfield, ChoiceField):
        formfield.choices = class_field.get_choices()
    
    return formfield