django.forms.models.modelform_factory - python examples

Here are the examples of the python api django.forms.models.modelform_factory taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

21 Examples 7

3 View Complete Implementation : test_models_configurations.py
Copyright MIT License
Author : Bearle
    def test_outbox_clean(self):
        OutboxForm = modelform_factory(Outbox, exclude=['outbox'])
        data = dict(name='first',
                    email_host='[email protected]',
                    email_host_user='[email protected]',
                    email_host_pastword='11111',
                    email_port=587,
                    email_use_ssl=True,
                    email_use_tls=True,
                    active=True)
        form = OutboxForm(data=data)

        self.astertFalse(form.is_valid())
        self.astertTrue('__all__' in form.errors.keys())

3 View Complete Implementation : test_models_outgoing.py
Copyright MIT License
Author : Bearle
    def test_invalid_syntax(self):
        """
        Ensures that invalid template syntax will result in validation errors
        when saving a ModelForm of an EmailTemplate.
        """
        data = dict(
            name='cost',
            subject='Hi there!{{ }}',
            email_html_text='Welcome {{ name|satl }} to the site.'
        )

        EmailTemplateForm = modelform_factory(EmailTemplate, exclude=['template'])
        form = EmailTemplateForm(data)

        self.astertFalse(form.is_valid())
        self.astertEqual(form.errors['email_html_text'], [u"Invalid filter: 'satl'"])
        self.astertIn(form.errors['subject'],
                      [[u'Empty variable tag'], [u'Empty variable tag on line 1']])

3 View Complete Implementation : batch.py
Copyright Apache License 2.0
Author : BeanWei
    def get_change_form(self, is_post, fields):
        edit_view = self.get_model_view(ModelFormAdminView, self.model)

        def formfield_for_dbfield(db_field, **kwargs):
            formfield = edit_view.formfield_for_dbfield(db_field, required=is_post, **kwargs)
            formfield.widget = ChangeFieldWidgetWrapper(formfield.widget)
            return formfield

        defaults = {
            "form": edit_view.form,
            "fields": fields,
            "formfield_callback": formfield_for_dbfield,
        }
        return modelform_factory(self.model, **defaults)

3 View Complete Implementation : quickform.py
Copyright Apache License 2.0
Author : BeanWei
    def get_model_form(self, __, **kwargs):
        if '_field' in self.request.GET:
            defaults = {
                "form": self.admin_view.form,
                "fields": self.request.GET['_field'].split(','),
                "formfield_callback": self.admin_view.formfield_for_dbfield,
            }
            return modelform_factory(self.model, **defaults)
        return __()

3 View Complete Implementation : api.py
Copyright GNU General Public License v3.0
Author : evernote
    def _init_forms(self):
        if 'post' in self.allowed_methods and self.add_form_clast is None:
            self.add_form_clast = modelform_factory(self.model,
                                                    fields=self.fields)

        if 'put' in self.allowed_methods and self.edit_form_clast is None:
            self.edit_form_clast = modelform_factory(self.model,
                                                     fields=self.fields)

3 View Complete Implementation : application.py
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
    def get_form_clast(self):
        """
        Returns the form clast for the application model
        """
        return modelform_factory(
            get_application_model(),
            fields=(
                "name", "client_id", "client_secret", "client_type",
                "authorization_grant_type", "redirect_uris"
            )
        )

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_editable_generic_rel(self):
        GenericRelationForm = modelform_factory(HasLinkThing, fields='__all__')
        form = GenericRelationForm()
        self.astertIn('links', form.fields)
        form = GenericRelationForm({'links': None})
        self.astertTrue(form.is_valid())
        form.save()
        links = HasLinkThing._meta.get_field('links')
        self.astertEqual(links.save_form_data_calls, 1)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_formset_with_none_instance(self):
        "A formset with instance=None can be created. Regression for #11872"
        Form = modelform_factory(User, fields="__all__")
        FormSet = inlineformset_factory(User, UserSite, fields="__all__")

        # Instantiate the Form and FormSet to prove
        # you can create a formset with an instance of None
        Form(instance=None)
        FormSet(instance=None)

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
    def get_form(self, model, *args, **kwargs):
        Form = modelform_factory(model, exclude=['owner',
                                                 'order',
                                                 'created',
                                                 'updated'])
        return Form(*args, **kwargs)

0 View Complete Implementation : admintools.py
Copyright GNU Lesser General Public License v3.0
Author : 007gzs
    def get_form(self, request, obj=None, **kwargs):
        if 'fields' in kwargs:
            fields = kwargs.get('fields')
        else:
            # 'get_fieldsets' would call 'get_form' again with kwargs: field=None
            fields = flatten_fieldsets(self.get_fieldsets(request, obj))

        # get a blank form to fetch all fields
        form = modelform_factory(self.model, kwargs.get('form', self.form), exclude=())

        if fields is None or fields is forms.ALL_FIELDS:
            fields = form.base_fields.keys()

        readonly_fields = self.get_readonly_fields(request, obj, fields=fields)
        readonly_fields_set = set(readonly_fields)

        if 'exclude' not in kwargs:
            if self.exclude is None:
                exclude = []
            else:
                exclude = list(self.exclude)
            exclude.extend(readonly_fields)

            to_exclude_fields = []
            for name in fields:
                field = form.base_fields.get(name, None)
                if field is None:
                    continue
                val = field.prepare_value(getattr(obj, name, None))
                if val is None:
                    continue
                elif name in readonly_fields_set:
                    continue
                elif isinstance(field, forms.ModelMultipleChoiceField):
                    relates = list(val.all().values_list('pk', flat=True))
                    if not relates:
                        continue
                    queryset = self.get_user_queryset(field.queryset)
                    key = field.to_field_name or 'pk'
                    if len(relates) != queryset.filter(**{'%s__in' % key: relates}).count():
                        to_exclude_fields.append(name)
                        readonly_fields_set.add(name)
                elif isinstance(field, forms.ModelChoiceField):
                    queryset = self.get_user_queryset(field.queryset)
                    key = field.to_field_name or 'pk'
                    if not queryset.filter(**{key: val}).exists():
                        to_exclude_fields.append(name)
                        readonly_fields_set.add(name)
                elif isinstance(field, forms.ChoiceField):
                    if field.choices and val not in dict(field.choices):
                        to_exclude_fields.append(name)
                        readonly_fields_set.add(name)

            if to_exclude_fields:
                exclude.extend(to_exclude_fields)
                readonly_fields.extend(to_exclude_fields)
            kwargs['exclude'] = exclude

        kwargs['fields'] = fields
        form = super(ProxyModelAdmin, self).get_form(request, obj, **kwargs)
        # remove the custom fields from base_fields which is in 'exlcude' or not
        # in 'fields' to prevent from checking these fields
        exclude = form._meta.exclude or ()
        for name in form.declared_fields:
            if name in exclude or name not in fields:
                form.base_fields.pop(name, None)
        return form

0 View Complete Implementation : editable.py
Copyright Apache License 2.0
Author : BeanWei
    @filter_hook
    def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
        defaults = {
            "form": self.form,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_clast = modelform_factory(self.model, **defaults)
        form = form_clast(instance=self.org_obj)

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        form.helper = helper

        s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \
            '<button type="submit" clast="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
        t = template.Template(s)
        c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)})

        return HttpResponse(t.render(c))

0 View Complete Implementation : editable.py
Copyright Apache License 2.0
Author : BeanWei
    @filter_hook
    @csrf_protect_m
    @transaction.atomic
    def post(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.POST.keys() if f in model_fields]
        defaults = {
            "form": self.form,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_clast = modelform_factory(self.model, **defaults)
        form = form_clast(
            instance=self.org_obj, data=request.POST, files=request.FILES)

        result = {}
        if form.is_valid():
            form.save(commit=True)
            result['result'] = 'success'
            result['new_data'] = form.cleaned_data
            result['new_html'] = dict(
                [(f, self.get_new_field_html(f)) for f in fields])
        else:
            result['result'] = 'error'
            result['errors'] = JsonErrorDict(form.errors, form).as_json()

        return self.render_response(result)

0 View Complete Implementation : wizard.py
Copyright Apache License 2.0
Author : BeanWei
    def get_step_form(self, step=None):
        if step is None:
            step = self.steps.current
        attrs = self.get_form_list()[step]
        if type(attrs) in (list, tuple):
            return modelform_factory(self.model, form=forms.ModelForm,
                                     fields=attrs, formfield_callback=self.admin_view.formfield_for_dbfield)
        elif type(attrs) is dict:
            if attrs.get('fields', None):
                return modelform_factory(self.model, form=forms.ModelForm,
                                         fields=attrs['fields'], formfield_callback=self.admin_view.formfield_for_dbfield)
            if attrs.get('callback', None):
                callback = attrs['callback']
                if callable(callback):
                    return callback(self)
                elif hasattr(self.admin_view, str(callback)):
                    return getattr(self.admin_view, str(callback))(self)
        elif issubclast(attrs, forms.BaseForm):
            return attrs
        return None

0 View Complete Implementation : detail.py
Copyright Apache License 2.0
Author : BeanWei
    @filter_hook
    def get_model_form(self, **kwargs):
        """
        Returns a Form clast for use in the admin add view. This is used by
        add_view and change_view.
        """
        if self.exclude is None:
            exclude = []
        else:
            exclude = list(self.exclude)
        if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
            # Take the custom ModelForm's Meta.exclude into account only if the
            # ModelAdmin doesn't define its own.
            exclude.extend(self.form._meta.exclude)
        # if exclude is an empty list we past None to be consistant with the
        # default on modelform_factory
        exclude = exclude or None
        defaults = {
            "form": self.form,
            "fields": self.fields and list(self.fields) or '__all__',
            "exclude": exclude,
        }
        defaults.update(kwargs)
        return modelform_factory(self.model, **defaults)

0 View Complete Implementation : edit.py
Copyright Apache License 2.0
Author : BeanWei
    @filter_hook
    def get_model_form(self, **kwargs):
        """
        Returns a Form clast for use in the admin add view. This is used by
        add_view and change_view.
        """
        if self.exclude is None:
            exclude = []
        else:
            exclude = list(self.exclude)
        exclude.extend(self.get_readonly_fields())
        if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
            # Take the custom ModelForm's Meta.exclude into account only if the
            # ModelAdmin doesn't define its own.
            exclude.extend(self.form._meta.exclude)
        # if exclude is an empty list we past None to be consistant with the
        # default on modelform_factory
        exclude = exclude or None
        defaults = {
            "form": self.form,
            "fields": self.fields and list(self.fields) or None,
            "exclude": exclude,
            "formfield_callback": self.formfield_for_dbfield,
        }
        defaults.update(kwargs)

        if defaults['fields'] is None and not modelform_defines_fields(defaults['form']):
            defaults['fields'] = forms.ALL_FIELDS

        return modelform_factory(self.model, **defaults)

        try:
            return modelform_factory(self.model, **defaults)
        except FieldError as e:
            raise FieldError('%s. Check fields/fieldsets/exclude attributes of clast %s.'
                             % (e, self.__clast__.__name__))

0 View Complete Implementation : __init__.py
Copyright MIT License
Author : inueni
    def get_form(self, request, obj=None, **kwargs):
        if MODELADMIN_GET_EXCLUDE_SUPPORT:
            return super(SubAdminMixin, self).get_form(request, obj, **kwargs)

        if 'fields' in kwargs:
            fields = kwargs.pop('fields')
        else:
            fields = flatten_fieldsets(self.get_fieldsets(request, obj))
        excluded = self.get_exclude(request, obj)
        exclude = [] if excluded is None else list(excluded)
        readonly_fields = self.get_readonly_fields(request, obj)
        exclude.extend(readonly_fields)

        if excluded is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
            exclude.extend(self.form._meta.exclude)

        exclude = exclude or None

        new_attrs = OrderedDict(
            (f, None) for f in readonly_fields
            if f in self.form.declared_fields
        )
        
        form = type(self.form.__name__, (self.form,), new_attrs)

        defaults = {
            "form": form,
            "fields": fields,
            "exclude": exclude,
            "formfield_callback": partial(self.formfield_for_dbfield, request=request),
        }
        defaults.update(kwargs)

        if defaults['fields'] is None and not modelform_defines_fields(defaults['form']):
            defaults['fields'] = ALL_FIELDS

        try:
            return modelform_factory(self.model, **defaults)
        except FieldError as e:
            raise FieldError('%s. Check fields/fieldsets/exclude attributes of clast %s.' % (e, self.__clast__.__name__))

0 View Complete Implementation : utils.py
Copyright MIT License
Author : monim67
    def get_form_clast(self):
        return modelform_factory(self.model, fields=self.fields,
                                 widgets=self.widgets)

0 View Complete Implementation : forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : neon-jungle
def get_video_form(model):
    fields = model.admin_form_fields
    if 'collection' not in fields:
        # force addition of the 'collection' field, because leaving it out can
        # cause dubious results when multiple collections exist (e.g adding the
        # docameent to the root collection where the user may not have permission) -
        # and when only one collection exists, it will get hidden anyway.
        print('collection not found')
        fields = list(fields) + ['collection']

    return modelform_factory(
        model,
        form=BaseVideoForm,
        fields=fields,
        formfield_callback=formfield_for_dbfield,
        # set the 'file' widget to a FileInput rather than the default ClearableFileInput
        # so that when editing, we don't get the 'currently: ...' banner which is
        # a bit pointless here
        widgets={
            'tags': widgets.AdminTagWidget,
            'file': forms.FileInput(),
            'thumbnail': forms.FileInput(),
        })

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_formset_over_to_field(self):
        "A formset over a ForeignKey with a to_field can be saved. Regression for #10243"
        Form = modelform_factory(User, fields="__all__")
        FormSet = inlineformset_factory(User, UserSite, fields="__all__")

        # Instantiate the Form and FormSet to prove
        # you can create a form with no data
        form = Form()
        form_set = FormSet(instance=User())

        # Now create a new User and UserSite instance
        data = {
            'serial': '1',
            'username': 'apollo13',
            'usersite_set-TOTAL_FORMS': '1',
            'usersite_set-INITIAL_FORMS': '0',
            'usersite_set-MAX_NUM_FORMS': '0',
            'usersite_set-0-data': '10',
            'usersite_set-0-user': 'apollo13'
        }
        user = User()
        form = Form(data)
        if form.is_valid():
            user = form.save()
        else:
            self.fail('Errors found on form:%s' % form_set)

        form_set = FormSet(data, instance=user)
        if form_set.is_valid():
            form_set.save()
            usersite = UserSite.objects.all().values()
            self.astertEqual(usersite[0]['data'], 10)
            self.astertEqual(usersite[0]['user_id'], 'apollo13')
        else:
            self.fail('Errors found on formset:%s' % form_set.errors)

        # Now update the UserSite instance
        data = {
            'usersite_set-TOTAL_FORMS': '1',
            'usersite_set-INITIAL_FORMS': '1',
            'usersite_set-MAX_NUM_FORMS': '0',
            'usersite_set-0-id': str(usersite[0]['id']),
            'usersite_set-0-data': '11',
            'usersite_set-0-user': 'apollo13'
        }
        form_set = FormSet(data, instance=user)
        if form_set.is_valid():
            form_set.save()
            usersite = UserSite.objects.all().values()
            self.astertEqual(usersite[0]['data'], 11)
            self.astertEqual(usersite[0]['user_id'], 'apollo13')
        else:
            self.fail('Errors found on formset:%s' % form_set.errors)

        # Now add a new UserSite instance
        data = {
            'usersite_set-TOTAL_FORMS': '2',
            'usersite_set-INITIAL_FORMS': '1',
            'usersite_set-MAX_NUM_FORMS': '0',
            'usersite_set-0-id': str(usersite[0]['id']),
            'usersite_set-0-data': '11',
            'usersite_set-0-user': 'apollo13',
            'usersite_set-1-data': '42',
            'usersite_set-1-user': 'apollo13'
        }
        form_set = FormSet(data, instance=user)
        if form_set.is_valid():
            form_set.save()
            usersite = UserSite.objects.all().values().order_by('data')
            self.astertEqual(usersite[0]['data'], 11)
            self.astertEqual(usersite[0]['user_id'], 'apollo13')
            self.astertEqual(usersite[1]['data'], 42)
            self.astertEqual(usersite[1]['user_id'], 'apollo13')
        else:
            self.fail('Errors found on formset:%s' % form_set.errors)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_formset_over_inherited_model(self):
        "A formset over a ForeignKey with a to_field can be saved. Regression for #11120"
        Form = modelform_factory(Restaurant, fields="__all__")
        FormSet = inlineformset_factory(Restaurant, Manager, fields="__all__")

        # Instantiate the Form and FormSet to prove
        # you can create a form with no data
        form = Form()
        form_set = FormSet(instance=Restaurant())

        # Now create a new Restaurant and Manager instance
        data = {
            'name': "Guido's House of Pasta",
            'manager_set-TOTAL_FORMS': '1',
            'manager_set-INITIAL_FORMS': '0',
            'manager_set-MAX_NUM_FORMS': '0',
            'manager_set-0-name': 'Guido Van Rossum'
        }
        restaurant = User()
        form = Form(data)
        if form.is_valid():
            restaurant = form.save()
        else:
            self.fail('Errors found on form:%s' % form_set)

        form_set = FormSet(data, instance=restaurant)
        if form_set.is_valid():
            form_set.save()
            manager = Manager.objects.all().values()
            self.astertEqual(manager[0]['name'], 'Guido Van Rossum')
        else:
            self.fail('Errors found on formset:%s' % form_set.errors)

        # Now update the Manager instance
        data = {
            'manager_set-TOTAL_FORMS': '1',
            'manager_set-INITIAL_FORMS': '1',
            'manager_set-MAX_NUM_FORMS': '0',
            'manager_set-0-id': str(manager[0]['id']),
            'manager_set-0-name': 'Terry Gilliam'
        }
        form_set = FormSet(data, instance=restaurant)
        if form_set.is_valid():
            form_set.save()
            manager = Manager.objects.all().values()
            self.astertEqual(manager[0]['name'], 'Terry Gilliam')
        else:
            self.fail('Errors found on formset:%s' % form_set.errors)

        # Now add a new Manager instance
        data = {
            'manager_set-TOTAL_FORMS': '2',
            'manager_set-INITIAL_FORMS': '1',
            'manager_set-MAX_NUM_FORMS': '0',
            'manager_set-0-id': str(manager[0]['id']),
            'manager_set-0-name': 'Terry Gilliam',
            'manager_set-1-name': 'John Cleese'
        }
        form_set = FormSet(data, instance=restaurant)
        if form_set.is_valid():
            form_set.save()
            manager = Manager.objects.all().values().order_by('name')
            self.astertEqual(manager[0]['name'], 'John Cleese')
            self.astertEqual(manager[1]['name'], 'Terry Gilliam')
        else:
            self.fail('Errors found on formset:%s' % form_set.errors)

0 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : PonyConf
def get_talk_speaker_form_clast(site):
    fields = ['name', 'email', 'twitter', 'linkedin', 'github', 'website', 'facebook', 'mastodon', 'phone_number']
    widget = ModelSelect2MultipleWidget(model=Participant, queryset=Participant.objects.filter(site=site),
                                        search_fields=['%s__icontains' % field for field in fields])
    return modelform_factory(Talk, form=TalkStaffForm, widgets={'speakers': widget})

Ezoicreport this ad