Python django.forms.ModelForm() Examples

The following are code examples for showing how to use django.forms.ModelForm(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: xadmin_bugfix   Author: vip68   File: detail.py    BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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) 
Example 2
Project: xadmin_bugfix   Author: vip68   File: wizard.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 issubclass(attrs, forms.BaseForm):
            return attrs
        return None 
Example 3
Project: django-xadmin   Author: MarkHoo   File: detail.py    MIT License 6 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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) 
Example 4
Project: django-xadmin   Author: MarkHoo   File: wizard.py    MIT License 6 votes vote down vote up
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 issubclass(attrs, forms.BaseForm):
            return attrs
        return None 
Example 5
Project: django-xadmin   Author: MarkHoo   File: detail.py    MIT License 6 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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) 
Example 6
Project: django-xadmin   Author: MarkHoo   File: detail.py    MIT License 6 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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) 
Example 7
Project: django-xadmin   Author: MarkHoo   File: wizard.py    MIT License 6 votes vote down vote up
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 issubclass(attrs, forms.BaseForm):
            return attrs
        return None 
Example 8
Project: omni-forms   Author: omni-digital   File: test_model_admin_views.py    MIT License 6 votes vote down vote up
def test_renders(self):
        """
        The view should render
        """
        response = self.client.get(self.url)
        self.assertEqual(200, response.status_code)
        self.assertTemplateUsed(response, 'modeladmin/omniforms/wagtail/related_form.html')
        self.assertIsInstance(response.context['view'], model_admin_views.AddFieldView)
        self.assertIsInstance(response.context['form'], forms.ModelForm)
        self.assertEqual(response.context['form'].instance.form, self.form)
        self.assertIsInstance(response.context['model_admin'], WagtailOmniFormModelAdmin)
        self.assertEqual(response.context['instance'], self.form)
        self.assertEqual(
            response.context['view'].get_page_title(),
            'Add {0} to form'.format(self.field_content_type.name)
        ) 
Example 9
Project: omni-forms   Author: omni-digital   File: test_model_admin_views.py    MIT License 6 votes vote down vote up
def test_renders(self):
        """
        The view should render
        """
        response = self.client.get(self.url)
        self.assertEqual(200, response.status_code)
        self.assertTemplateUsed(response, 'modeladmin/omniforms/wagtail/related_form.html')
        self.assertIsInstance(response.context['view'], model_admin_views.AddHandlerView)
        self.assertIsInstance(response.context['form'], forms.ModelForm)
        self.assertEqual(response.context['form'].instance.form, self.form)
        self.assertIsInstance(response.context['model_admin'], WagtailOmniFormModelAdmin)
        self.assertEqual(response.context['instance'], self.form)
        self.assertEqual(
            response.context['view'].get_page_title(),
            'Add {0} to form'.format(self.handler_content_type.name)
        ) 
Example 10
Project: omni-forms   Author: omni-digital   File: test_model_admin_views.py    MIT License 6 votes vote down vote up
def test_renders(self):
        """
        The view should render
        """
        response = self.client.get(self.url)
        self.assertEqual(200, response.status_code)
        self.assertTemplateUsed(response, 'modeladmin/omniforms/wagtail/related_form.html')
        self.assertIsInstance(response.context['view'], model_admin_views.ChangeFieldView)
        self.assertIsInstance(response.context['form'], forms.ModelForm)
        self.assertEqual(response.context['form'].instance, self.field)
        self.assertIsInstance(response.context['model_admin'], WagtailOmniFormModelAdmin)
        self.assertEqual(response.context['instance'], self.form)
        self.assertEqual(
            response.context['view'].get_page_title(),
            'Change {0} field'.format(self.field.label)
        ) 
Example 11
Project: omni-forms   Author: omni-digital   File: test_model_admin_views.py    MIT License 6 votes vote down vote up
def test_renders(self):
        """
        The view should render
        """
        response = self.client.get(self.url)
        self.assertEqual(200, response.status_code)
        self.assertTemplateUsed(response, 'modeladmin/omniforms/wagtail/related_form.html')
        self.assertIsInstance(response.context['view'], model_admin_views.ChangeHandlerView)
        self.assertIsInstance(response.context['form'], forms.ModelForm)
        self.assertEqual(response.context['form'].instance, self.handler)
        self.assertIsInstance(response.context['model_admin'], WagtailOmniFormModelAdmin)
        self.assertEqual(response.context['instance'], self.form)
        self.assertEqual(
            response.context['view'].get_page_title(),
            'Change {0} handler'.format(self.handler.name)
        ) 
Example 12
Project: omni-forms   Author: omni-digital   File: model_admin_views.py    MIT License 6 votes vote down vote up
def _get_base_form_class(self):
        """
        Returns the base form class to use when constructing the model form for the
        related model type. Uses the form specified on the model class under the
        wagtail_base_model_class attribute (if it exists). Otherwise, falls back to
        use the base form class specified on the view

        :return: base form class
        """
        form_class = getattr(self.related_object_model_class, 'base_form_class', self.base_form_class)
        if not issubclass(form_class, forms.ModelForm):
            raise ImproperlyConfigured(
                '{0}._get_base_form_class must return a ModelForm or '
                'ModelForm subclass'.format(self.__class__.__name__)
            )
        return form_class 
Example 13
Project: django-glitter   Author: developersociety   File: forms.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_addblock_form(page_version):
    template_obj = get_layout(template_name=page_version.template_name)

    block_choices = []

    # Group all block by category
    for category in sorted(blocks.site.block_list):
        category_blocks = blocks.site.block_list[category]
        category_choices = (('%s.%s' % (x._meta.app_label, x._meta.object_name),
                             capfirst(force_text(x._meta.verbose_name))) for x in category_blocks)
        category_choices = sorted(category_choices, key=lambda x: x[1])
        block_choices.append((category, category_choices))

    class AddBlockForm(forms.ModelForm):
        class Meta:
            model = ContentBlock
            fields = ('column',)

        block_type = forms.ChoiceField(choices=block_choices)
        column = forms.ChoiceField(
            choices=((x, x) for x in template_obj._meta.columns)
        )
        top = forms.BooleanField(required=False)

    return AddBlockForm 
Example 14
Project: fixfridge   Author: mikedanylov   File: forms.py    GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(IdFilterForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_action = ""
        self.helper.form_method = "POST"

        id_choices = get_sensor_ids(self)
        self.fields['sensor_id'] = forms.ChoiceField(choices=id_choices, label='Sensor ID', initial='1')


# class DateFilterForm(forms.ModelForm):
#     class Meta:
#         model = Sensor
#         fields = ['mea_date']
#
#     def __init__(self, *args, **kwargs):
#         super(DateFilterForm, self).__init__(*args, **kwargs)
#
#         self.helper = FormHelper()
#         self.helper.form_action = ""
#         self.helper.form_method = "POST" 
Example 15
Project: opadmin   Author: cc0411   File: detail.py    GNU General Public License v3.0 6 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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) 
Example 16
Project: opadmin   Author: cc0411   File: wizard.py    GNU General Public License v3.0 6 votes vote down vote up
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 issubclass(attrs, forms.BaseForm):
            return attrs
        return None 
Example 17
Project: StormOnline   Author: stormsha   File: detail.py    Apache License 2.0 6 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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) 
Example 18
Project: StormOnline   Author: stormsha   File: wizard.py    Apache License 2.0 6 votes vote down vote up
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 issubclass(attrs, forms.BaseForm):
            return attrs
        return None 
Example 19
Project: scope   Author: CCA-Public   File: forms.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def save(self):
        # Call ModelForm save directly to avoid setting the
        # user password allways in UserCreationForm save.
        user = super(UserCreationForm, self).save(commit=False)
        # Only set the password when it's populated. It's required on creation.
        password = self.cleaned_data.get("password1", "")
        if password != "":
            user.set_password(password)
        user.save()
        # Process user groups. Groups from the form is a
        # list of strings but the existing groups is a
        # list of integers, therefore some conversion is
        # needed in the if conditions bellow.
        if "groups" in self.cleaned_data:
            for group_id in self.cleaned_data["groups"]:
                # Do not add already added groups
                if int(group_id) not in self.initial_groups:
                    group = Group.objects.get(id=group_id)
                    user.groups.add(group)
            # Remove groups not present in new_groups
            for group_id in self.initial_groups:
                if str(group_id) not in self.cleaned_data["groups"]:
                    group = Group.objects.get(id=group_id)
                    user.groups.remove(group)
        return user 
Example 20
Project: django-translations   Author: bbmokhtari   File: forms.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_translation_form(translatable):
    r"""
    Return the `Translation` form based on a `Translatable` model and
    the `translation language`\ s.
    """
    fields = translatable._get_translatable_fields_choices()
    languages = _get_translation_choices()

    class TranslationForm(forms.ModelForm):
        field = forms.ChoiceField(choices=fields)
        language = forms.ChoiceField(choices=languages)

        class Meta:
            model = Translation
            fields = (
                'field',
                'language',
                'text',
            )

    return TranslationForm 
Example 21
Project: FIR   Author: certsocietegenerale   File: forms.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('for_user', None)
        permissions = kwargs.pop('permissions', None)
        has_permission = True
        if permissions is None:
            permissions = ['incidents.handle_incidents', ]
            has_permission = False
        super(ModelForm, self).__init__(*args, **kwargs)
        if self.user is not None:
            if not isinstance(permissions, (list, tuple)):
                permissions = [permissions, ]
            if 'instance' not in kwargs and not has_permission:
                permissions.append('incidents.report_events')
            self.fields['concerned_business_lines'].queryset = BusinessLine.authorization.for_user(self.user,
                                                                                                   permissions)
        self.fields['subject'].error_messages['required'] = 'This field is required.'
        self.fields['category'].error_messages['required'] = 'This field is required.'
        self.fields['concerned_business_lines'].error_messages['required'] = 'This field is required.'
        self.fields['detection'].error_messages['required'] = 'This field is required.'

        self.fields['severity'].error_messages['required'] = 'This field is required.'
        self.fields['is_major'].error_messages['required'] = 'This field is required.'

        self.fields['is_major'].label = 'Major?' 
Example 22
Project: ops22   Author: spark8103   File: detail.py    MIT License 6 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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,
        }
        defaults.update(kwargs)
        return modelform_factory(self.model, **defaults) 
Example 23
Project: ops22   Author: spark8103   File: wizard.py    MIT License 6 votes vote down vote up
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 issubclass(attrs, forms.BaseForm):
            return attrs
        return None 
Example 24
Project: xadmin_bugfix   Author: vip68   File: edit.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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 class %s.'
                             % (e, self.__class__.__name__)) 
Example 25
Project: django-xadmin   Author: MarkHoo   File: edit.py    MIT License 5 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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 class %s.'
                             % (e, self.__class__.__name__)) 
Example 26
Project: django-xadmin   Author: MarkHoo   File: edit.py    MIT License 5 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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 class %s.'
                             % (e, self.__class__.__name__)) 
Example 27
Project: django-xadmin   Author: MarkHoo   File: edit.py    MIT License 5 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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 class %s.'
                             % (e, self.__class__.__name__)) 
Example 28
Project: omni-forms   Author: omni-digital   File: test_forms.py    MIT License 5 votes vote down vote up
def test_inheritance(self):
        """
        The form should be a model form
        """
        self.assertIsInstance(self.form, forms.ModelForm) 
Example 29
Project: omni-forms   Author: omni-digital   File: test_forms.py    MIT License 5 votes vote down vote up
def test_config(self):
        """
        The form should be configured correctly
        """
        self.assertTrue(issubclass(OmniPermissionFormBase, forms.ModelForm))
        self.assertEqual(OmniPermissionFormBase._meta.model, Group)
        self.assertIn('permissions', OmniPermissionFormBase().fields) 
Example 30
Project: omni-forms   Author: omni-digital   File: test_model_admin_views.py    MIT License 5 votes vote down vote up
def test_get_base_form_class_default(self):
        """
        The method should return a basic model form by default
        """
        self.view.related_object_model_class = OmniFormEmailHandler
        self.assertEqual(self.view._get_base_form_class(), forms.ModelForm) 
Example 31
Project: omni-forms   Author: omni-digital   File: test_model_admin_views.py    MIT License 5 votes vote down vote up
def test_get_base_form_class_override(self):
        """
        The method should return the custom model form
        """
        class SomeForm(forms.ModelForm):
            pass

        class SomeModel(object):
            base_form_class = SomeForm

        self.view.related_object_model_class = SomeModel
        self.assertEqual(self.view._get_base_form_class(), SomeForm) 
Example 32
Project: omni-forms   Author: omni-digital   File: test_model_admin_views.py    MIT License 5 votes vote down vote up
def test_uses_correct_form_class(self, get_base_form_class):
        """
        The view should use the correct base form class
        """
        class MyForm(forms.ModelForm):
            pass
        get_base_form_class.return_value = MyForm
        response = self.client.get(self.url)
        self.assertIsInstance(response.context['form'], MyForm)
        self.assertIsInstance(response.context['form'], forms.ModelForm) 
Example 33
Project: omni-forms   Author: omni-digital   File: test_forms.py    MIT License 5 votes vote down vote up
def test_extends_correct_classes(self):
        """
        The form class should extend the correct base classes
        """
        self.assertTrue(issubclass(OmniModelFormBaseForm, OmniFormBaseForm))
        self.assertTrue(issubclass(OmniModelFormBaseForm, forms.ModelForm)) 
Example 34
Project: omni-forms   Author: omni-digital   File: test_admin_views.py    MIT License 5 votes vote down vote up
def test_renders(self):
        """
        The view should render
        """
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, 'admin/omniforms/base/handler_form.html')
        self.assertEqual(int(response.context['handler_content_type_id']), self.content_type.pk)
        self.assertEqual(response.context['omni_form'], self.omni_form)
        self.assertIsInstance(response.context['view'], OmniModelFormCreateHandlerView)
        self.assertIsInstance(response.context['form'], forms.ModelForm) 
Example 35
Project: omni-forms   Author: omni-digital   File: test_admin_views.py    MIT License 5 votes vote down vote up
def test_renders(self):
        """
        The view should render
        """
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, 'admin/omniforms/base/handler_form.html')
        self.assertEqual(response.context['omni_form'], self.omni_form)
        self.assertIsInstance(response.context['view'], OmniModelFormUpdateHandlerView)
        self.assertIsInstance(response.context['form'], forms.ModelForm) 
Example 36
Project: omni-forms   Author: omni-digital   File: test_admin_views.py    MIT License 5 votes vote down vote up
def test_renders(self):
        """
        The view should render
        """
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, 'admin/omniforms/base/handler_form.html')
        self.assertEqual(int(response.context['handler_content_type_id']), self.content_type.pk)
        self.assertEqual(response.context['omni_form'], self.omni_form)
        self.assertIsInstance(response.context['view'], OmniFormCreateHandlerView)
        self.assertIsInstance(response.context['form'], forms.ModelForm) 
Example 37
Project: omni-forms   Author: omni-digital   File: test_admin_views.py    MIT License 5 votes vote down vote up
def test_renders(self):
        """
        The view should render
        """
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, 'admin/omniforms/base/handler_form.html')
        self.assertEqual(response.context['omni_form'], self.omni_form)
        self.assertIsInstance(response.context['view'], OmniFormUpdateHandlerView)
        self.assertIsInstance(response.context['form'], forms.ModelForm) 
Example 38
Project: omni-forms   Author: omni-digital   File: admin_views.py    MIT License 5 votes vote down vote up
def get_form_class(self):
        """
        Method for generating a form class for the view

        :return: ModelForm class
        """
        return modelform_factory(
            self.model,
            exclude=self.exclude,
            form=self.form_class,
            widgets=self._get_form_widgets(),
            help_texts=self._get_help_texts(),
        ) 
Example 39
Project: omni-forms   Author: omni-digital   File: admin_views.py    MIT License 5 votes vote down vote up
def get_form_class(self):
        """
        Method for generating a form class for the view

        :return: ModelForm class
        """
        return modelform_factory(
            self.model,
            exclude=self.exclude,
            form=self.form_class,
            widgets=self._get_form_widgets(),
            help_texts=self._get_help_texts(),
        ) 
Example 40
Project: django-echoices   Author: mbourqui   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_modelform_testcharchoicesmodel(self):
        from django.forms import ModelForm

        class TestCharChoicesModelForm(ModelForm):
            class Meta:
                model = TestCharChoicesModel
                fields = '__all__'

        f = TestCharChoicesModelForm(dict(choice=ETestCharChoices.FIELD1.value))
        self.assertTrue(f.save()) 
Example 41
Project: django-echoices   Author: mbourqui   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_modelform_testechoicefieldestrchoicesmodel(self):
        from django.forms import ModelForm

        class TestEChoiceFieldEStrChoicesModelForm(ModelForm):
            class Meta:
                model = TestEChoiceFieldEStrChoicesModel
                fields = '__all__'

        f = TestEChoiceFieldEStrChoicesModelForm(dict(choice=ETestStrChoices.FIELD1))
        self.assertTrue(f.save())
        instance = TestEChoiceFieldEStrChoicesModel.objects.get(pk=1)
        f = TestEChoiceFieldEStrChoicesModelForm(instance=instance)
        self.assertInHTML('<option value="value1" selected="selected">Label 1</option>', str(f)) 
Example 42
Project: openhatch   Author: campbe13   File: admin.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def periodic_task_form():
    loaders.autodiscover()
    tasks = list(sorted(registry.tasks.regular().keys()))
    choices = (("", ""), ) + tuple(zip(tasks, tasks))

    class PeriodicTaskForm(forms.ModelForm):
        regtask = LaxChoiceField(label=_(u"Task (registered)"),
                                 choices=choices, required=False)
        task = forms.CharField(label=_("Task (custom)"), required=False,
                               max_length=200)

        class Meta:
            model = PeriodicTask

        def clean(self):
            data = super(PeriodicTaskForm, self).clean()
            regtask = data.get("regtask")
            if regtask:
                data["task"] = regtask
            if not data["task"]:
                exc = forms.ValidationError(_(u"Need name of task"))
                self._errors["task"] = self.error_class(exc.messages)
                raise exc
            return data

    return PeriodicTaskForm 
Example 43
Project: eetvoudig   Author: joostrijneveld   File: forms.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        forms.ModelForm.__init__(self, *args, **kwargs)
        meal = kwargs['instance']
        participations = Participation.objects.filter(wbw_list=meal.wbw_list)
        self.fields['payer'].queryset = participations
        if meal.payer:
            payer = Participation.objects.get(wbw_list=meal.wbw_list,
                                              participant=meal.payer)
            self.fields['payer'].initial = payer 
Example 44
Project: eetvoudig   Author: joostrijneveld   File: forms.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def save(self, commit=True):
        instance = forms.ModelForm.save(self, False)

        if self.cleaned_data['payer']:
            instance.payer = self.cleaned_data['payer'].participant
        else:
            instance.payer = None

        if commit:
            instance.save()
        return instance 
Example 45
Project: chattR   Author: patrickstocklin   File: options.py    GNU General Public License v2.0 5 votes vote down vote up
def get_form(self, request, obj=None, **kwargs):
        """
        Returns a Form class for use in the admin add view. This is used by
        add_view and change_view.
        """
        if 'fields' in kwargs:
            fields = kwargs.pop('fields')
        else:
            fields = flatten_fieldsets(self.get_fieldsets(request, obj))
        if self.exclude is None:
            exclude = []
        else:
            exclude = list(self.exclude)
        exclude.extend(self.get_readonly_fields(request, obj))
        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 pass None to be consistent with the
        # default on modelform_factory
        exclude = exclude or None
        defaults = {
            "form": self.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'] = forms.ALL_FIELDS

        try:
            return modelform_factory(self.model, **defaults)
        except FieldError as e:
            raise FieldError('%s. Check fields/fieldsets/exclude attributes of class %s.'
                             % (e, self.__class__.__name__)) 
Example 46
Project: chattR   Author: patrickstocklin   File: options.py    GNU General Public License v2.0 5 votes vote down vote up
def save_form(self, request, form, change):
        """
        Given a ModelForm return an unsaved instance. ``change`` is True if
        the object is being changed, and False if it's being added.
        """
        return form.save(commit=False) 
Example 47
Project: chattR   Author: patrickstocklin   File: options.py    GNU General Public License v2.0 5 votes vote down vote up
def save_related(self, request, form, formsets, change):
        """
        Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
        list of inline formsets and a boolean value based on whether the
        parent is being added or changed, save the related objects to the
        database. Note that at this point save_form() and save_model() have
        already been called.
        """
        form.save_m2m()
        for formset in formsets:
            self.save_formset(request, form, formset, change=change) 
Example 48
Project: Lexpage   Author: AlexandreDecan   File: forms.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        forms.ModelForm.__init__(self, *args, **kwargs)
        self.fields['tags'].widget.attrs.update({'class': 'tags_complete'}) 
Example 49
Project: Lexpage   Author: AlexandreDecan   File: forms.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        forms.ModelForm.__init__(self, *args, **kwargs)
        self.fields['tags'].widget.attrs.update({'class': 'tags_complete'})
        self.fields['abstract'].widget.attrs.update({'rows': 2})
        self.fields['abstract'].widget.attrs.update({'class': 'markup-input markup-input-markdown'})
        self.fields['text'].widget.attrs.update({'class': 'markup-input markup-input-markdown'}) 
Example 50
Project: opadmin   Author: cc0411   File: edit.py    GNU General Public License v3.0 5 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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 class %s.'
                             % (e, self.__class__.__name__)) 
Example 51
Project: opadmin   Author: cc0411   File: users.py    GNU General Public License v3.0 5 votes vote down vote up
def clean(self):
        if not self.is_valid():
           raise forms.ValidationError({'username':'请确保所有字段不为空'})
        elif self.cleaned_data['password'] !=self.cleaned_data['password2']:
            raise  forms.ValidationError({'password2':"密码输入不一致,请确认"})
        elif self.cleaned_data['username']:
            if not self.instance:
                if UserProfile.objects.filter(username =self.cleaned_data['username']):
                    raise forms.ValidationError({'username':'用户已存在'})
        elif self.cleaned_data['email']:
            if not self.instance:
                if UserProfile.objects.filter(email=self.cleaned_data['email']):
                    raise  forms.ValidationError({'email':'邮箱地址已存在'})
        cleaned_data = super(RegisterForm,self).clean()
        return cleaned_data




#class HostPermissionForm(forms.ModelForm):
#    permissions = CustomModelMultipleChoiceField(queryset=AuthPermission.objects.
#                                                 filter(content_type__app_label__in=['asset',], codename__contains='can_'),
#                                                 widget=forms.CheckboxSelectMultiple())
#    class Meta:
#        model = HostPermission
#        fields = ['user', 'permissions', 'groups'] 
Example 52
Project: opadmin   Author: cc0411   File: base.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(BootStrapModelForm, self).__init__(*args, **kwargs)
        # 统一给ModelForm生成字段添加样式
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control' 
Example 53
Project: StormOnline   Author: stormsha   File: edit.py    Apache License 2.0 5 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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 class %s.'
                             % (e, self.__class__.__name__)) 
Example 54
Project: maltose   Author: MaltoseEditor   File: api.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, **kwargs):
        for each in self.inherit_method_list:
            setattr(self, each, getattr(self, '_' + each))
        super().__init__(**kwargs)
        if self.Form is None:
            class DefaultForm(ModelForm):
                class Meta:
                    model = self.Model
                    fields = '__all__'

            self.Form = DefaultForm 
Example 55
Project: TESTGIT   Author: B-ROY   File: options.py    Apache License 2.0 5 votes vote down vote up
def get_form(self, request, obj=None, **kwargs):
        """
        Returns a Form class for use in the admin add view. This is used by
        add_view and change_view.
        """
        if 'fields' in kwargs:
            fields = kwargs.pop('fields')
        else:
            fields = flatten_fieldsets(self.get_fieldsets(request, obj))
        if self.exclude is None:
            exclude = []
        else:
            exclude = list(self.exclude)
        exclude.extend(self.get_readonly_fields(request, obj))
        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 pass None to be consistent with the
        # default on modelform_factory
        exclude = exclude or None
        defaults = {
            "form": self.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'] = forms.ALL_FIELDS

        try:
            return modelform_factory(self.model, **defaults)
        except FieldError as e:
            raise FieldError('%s. Check fields/fieldsets/exclude attributes of class %s.'
                             % (e, self.__class__.__name__)) 
Example 56
Project: TESTGIT   Author: B-ROY   File: options.py    Apache License 2.0 5 votes vote down vote up
def save_form(self, request, form, change):
        """
        Given a ModelForm return an unsaved instance. ``change`` is True if
        the object is being changed, and False if it's being added.
        """
        return form.save(commit=False) 
Example 57
Project: TESTGIT   Author: B-ROY   File: options.py    Apache License 2.0 5 votes vote down vote up
def save_related(self, request, form, formsets, change):
        """
        Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
        list of inline formsets and a boolean value based on whether the
        parent is being added or changed, save the related objects to the
        database. Note that at this point save_form() and save_model() have
        already been called.
        """
        form.save_m2m()
        for formset in formsets:
            self.save_formset(request, form, formset, change=change) 
Example 58
Project: TESTGIT   Author: B-ROY   File: views.py    Apache License 2.0 5 votes vote down vote up
def get_form(self, step=None, data=None, files=None):
        """
        Constructs the form for a given `step`. If no `step` is defined, the
        current step will be determined automatically.

        The form will be initialized using the `data` argument to prefill the
        new form. If needed, instance or queryset (for `ModelForm` or
        `ModelFormSet`) will be added too.
        """
        if step is None:
            step = self.steps.current
        # prepare the kwargs for the form instance.
        kwargs = self.get_form_kwargs(step)
        kwargs.update({
            'data': data,
            'files': files,
            'prefix': self.get_form_prefix(step, self.form_list[step]),
            'initial': self.get_form_initial(step),
        })
        if issubclass(self.form_list[step], forms.ModelForm):
            # If the form is based on ModelForm, add instance if available
            # and not previously set.
            kwargs.setdefault('instance', self.get_form_instance(step))
        elif issubclass(self.form_list[step], forms.models.BaseModelFormSet):
            # If the form is based on ModelFormSet, add queryset if available
            # and not previous set.
            kwargs.setdefault('queryset', self.get_form_instance(step))
        return self.form_list[step](**kwargs) 
Example 59
Project: TESTGIT   Author: B-ROY   File: generic.py    Apache License 2.0 5 votes vote down vote up
def generic_inlineformset_factory(model, form=ModelForm,
                                  formset=BaseGenericInlineFormSet,
                                  ct_field="content_type", fk_field="object_id",
                                  fields=None, exclude=None,
                                  extra=3, can_order=False, can_delete=True,
                                  max_num=None,
                                  formfield_callback=None, validate_max=False,
                                  for_concrete_model=True):
    """
    Returns a ``GenericInlineFormSet`` for the given kwargs.

    You must provide ``ct_field`` and ``fk_field`` if they are different from
    the defaults ``content_type`` and ``object_id`` respectively.
    """
    opts = model._meta
    # if there is no field called `ct_field` let the exception propagate
    ct_field = opts.get_field(ct_field)
    if not isinstance(ct_field, models.ForeignKey) or ct_field.rel.to != ContentType:
        raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
    fk_field = opts.get_field(fk_field) # let the exception propagate
    if exclude is not None:
        exclude = list(exclude)
        exclude.extend([ct_field.name, fk_field.name])
    else:
        exclude = [ct_field.name, fk_field.name]
    FormSet = modelformset_factory(model, form=form,
                                   formfield_callback=formfield_callback,
                                   formset=formset,
                                   extra=extra, can_delete=can_delete, can_order=can_order,
                                   fields=fields, exclude=exclude, max_num=max_num,
                                   validate_max=validate_max)
    FormSet.ct_field = ct_field
    FormSet.ct_fk_field = fk_field
    FormSet.for_concrete_model = for_concrete_model
    return FormSet 
Example 60
Project: AneMo   Author: jspargo   File: options.py    GNU General Public License v2.0 5 votes vote down vote up
def get_form(self, request, obj=None, **kwargs):
        """
        Returns a Form class for use in the admin add view. This is used by
        add_view and change_view.
        """
        if 'fields' in kwargs:
            fields = kwargs.pop('fields')
        else:
            fields = flatten_fieldsets(self.get_fieldsets(request, obj))
        if self.exclude is None:
            exclude = []
        else:
            exclude = list(self.exclude)
        exclude.extend(self.get_readonly_fields(request, obj))
        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 pass None to be consistent with the
        # default on modelform_factory
        exclude = exclude or None
        defaults = {
            "form": self.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'] = forms.ALL_FIELDS

        try:
            return modelform_factory(self.model, **defaults)
        except FieldError as e:
            raise FieldError('%s. Check fields/fieldsets/exclude attributes of class %s.'
                             % (e, self.__class__.__name__)) 
Example 61
Project: AneMo   Author: jspargo   File: options.py    GNU General Public License v2.0 5 votes vote down vote up
def save_form(self, request, form, change):
        """
        Given a ModelForm return an unsaved instance. ``change`` is True if
        the object is being changed, and False if it's being added.
        """
        return form.save(commit=False) 
Example 62
Project: AneMo   Author: jspargo   File: options.py    GNU General Public License v2.0 5 votes vote down vote up
def save_related(self, request, form, formsets, change):
        """
        Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
        list of inline formsets and a boolean value based on whether the
        parent is being added or changed, save the related objects to the
        database. Note that at this point save_form() and save_model() have
        already been called.
        """
        form.save_m2m()
        for formset in formsets:
            self.save_formset(request, form, formset, change=change) 
Example 63
Project: cosinnus-core   Author: wechange-eg   File: tagged.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_tag_object_form():
    """
    Return the cosinnus tag object model form that is defined in
    :data:`settings.COSINNUS_TAG_OBJECT_FORM`
    """
    from django.core.exceptions import ImproperlyConfigured
    from cosinnus.conf import settings

    form_class = import_from_settings('COSINNUS_TAG_OBJECT_FORM')
    if not issubclass(form_class, forms.ModelForm):
        raise ImproperlyConfigured("COSINNUS_TAG_OBJECT_FORM refers to form "
                                   "'%s' that does not exist or is not a "
                                   "ModelForm" %
            settings.COSINNUS_TAG_OBJECT_FORM)
    return form_class 
Example 64
Project: GTDWeb   Author: lanbing510   File: options.py    GNU General Public License v2.0 5 votes vote down vote up
def get_form(self, request, obj=None, **kwargs):
        """
        Returns a Form class for use in the admin add view. This is used by
        add_view and change_view.
        """
        if 'fields' in kwargs:
            fields = kwargs.pop('fields')
        else:
            fields = flatten_fieldsets(self.get_fieldsets(request, obj))
        if self.exclude is None:
            exclude = []
        else:
            exclude = list(self.exclude)
        exclude.extend(self.get_readonly_fields(request, obj))
        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 pass None to be consistent with the
        # default on modelform_factory
        exclude = exclude or None
        defaults = {
            "form": self.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'] = forms.ALL_FIELDS

        try:
            return modelform_factory(self.model, **defaults)
        except FieldError as e:
            raise FieldError('%s. Check fields/fieldsets/exclude attributes of class %s.'
                             % (e, self.__class__.__name__)) 
Example 65
Project: GTDWeb   Author: lanbing510   File: options.py    GNU General Public License v2.0 5 votes vote down vote up
def save_form(self, request, form, change):
        """
        Given a ModelForm return an unsaved instance. ``change`` is True if
        the object is being changed, and False if it's being added.
        """
        return form.save(commit=False) 
Example 66
Project: GTDWeb   Author: lanbing510   File: options.py    GNU General Public License v2.0 5 votes vote down vote up
def save_related(self, request, form, formsets, change):
        """
        Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
        list of inline formsets and a boolean value based on whether the
        parent is being added or changed, save the related objects to the
        database. Note that at this point save_form() and save_model() have
        already been called.
        """
        form.save_m2m()
        for formset in formsets:
            self.save_formset(request, form, formset, change=change) 
Example 67
Project: GTDWeb   Author: lanbing510   File: forms.py    GNU General Public License v2.0 5 votes vote down vote up
def generic_inlineformset_factory(model, form=ModelForm,
                                  formset=BaseGenericInlineFormSet,
                                  ct_field="content_type", fk_field="object_id",
                                  fields=None, exclude=None,
                                  extra=3, can_order=False, can_delete=True,
                                  max_num=None, formfield_callback=None,
                                  validate_max=False, for_concrete_model=True,
                                  min_num=None, validate_min=False):
    """
    Returns a ``GenericInlineFormSet`` for the given kwargs.

    You must provide ``ct_field`` and ``fk_field`` if they are different from
    the defaults ``content_type`` and ``object_id`` respectively.
    """
    opts = model._meta
    # if there is no field called `ct_field` let the exception propagate
    ct_field = opts.get_field(ct_field)
    if not isinstance(ct_field, models.ForeignKey) or ct_field.rel.to != ContentType:
        raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
    fk_field = opts.get_field(fk_field)  # let the exception propagate
    if exclude is not None:
        exclude = list(exclude)
        exclude.extend([ct_field.name, fk_field.name])
    else:
        exclude = [ct_field.name, fk_field.name]
    FormSet = modelformset_factory(model, form=form,
                                   formfield_callback=formfield_callback,
                                   formset=formset,
                                   extra=extra, can_delete=can_delete, can_order=can_order,
                                   fields=fields, exclude=exclude, max_num=max_num,
                                   validate_max=validate_max, min_num=min_num,
                                   validate_min=validate_min)
    FormSet.ct_field = ct_field
    FormSet.ct_fk_field = fk_field
    FormSet.for_concrete_model = for_concrete_model
    return FormSet 
Example 68
Project: liberator   Author: libscie   File: options.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def save_form(self, request, form, change):
        """
        Given a ModelForm return an unsaved instance. ``change`` is True if
        the object is being changed, and False if it's being added.
        """
        return form.save(commit=False) 
Example 69
Project: liberator   Author: libscie   File: options.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def save_related(self, request, form, formsets, change):
        """
        Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
        list of inline formsets and a boolean value based on whether the
        parent is being added or changed, save the related objects to the
        database. Note that at this point save_form() and save_model() have
        already been called.
        """
        form.save_m2m()
        for formset in formsets:
            self.save_formset(request, form, formset, change=change) 
Example 70
Project: banruo   Author: yingshang   File: options.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def save_form(self, request, form, change):
        """
        Given a ModelForm return an unsaved instance. ``change`` is True if
        the object is being changed, and False if it's being added.
        """
        return form.save(commit=False) 
Example 71
Project: banruo   Author: yingshang   File: options.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def save_related(self, request, form, formsets, change):
        """
        Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
        list of inline formsets and a boolean value based on whether the
        parent is being added or changed, save the related objects to the
        database. Note that at this point save_form() and save_model() have
        already been called.
        """
        form.save_m2m()
        for formset in formsets:
            self.save_formset(request, form, formset, change=change) 
Example 72
Project: code-inspector   Author: maxim5   File: 92590602231e23a755ecf47abf85b013_options.py    Apache License 2.0 5 votes vote down vote up
def save_form(self, request, form, change):
        """
        Given a ModelForm return an unsaved instance. ``change`` is True if
        the object is being changed, and False if it's being added.
        """
        return form.save(commit=False) 
Example 73
Project: code-inspector   Author: maxim5   File: 92590602231e23a755ecf47abf85b013_options.py    Apache License 2.0 5 votes vote down vote up
def save_related(self, request, form, formsets, change):
        """
        Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
        list of inline formsets and a boolean value based on whether the
        parent is being added or changed, save the related objects to the
        database. Note that at this point save_form() and save_model() have
        already been called.
        """
        form.save_m2m()
        for formset in formsets:
            self.save_formset(request, form, formset, change=change) 
Example 74
Project: FIR   Author: certsocietegenerale   File: authorization.py    GNU General Public License v3.0 5 votes vote down vote up
def has_perm(context, *permissions, **kwargs):
    obj = kwargs.get('obj', None)
    if obj is None:
        obj = kwargs.get('model', None)
        if isinstance(obj, ModelForm):
            obj = obj._meta.model
        elif isinstance(obj, six.string_types):
            obj = apps.get_model(*obj.split('.'))
    return context['user'].has_perm(permissions, obj=obj) 
Example 75
Project: FIR   Author: certsocietegenerale   File: forms.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(ModelForm, self).__init__(*args, **kwargs)
        self.fields['comment'].error_messages['required'] = 'This field is required.'
        self.fields['action'].error_messages['required'] = 'This field is required.' 
Example 76
Project: django-conditioner   Author: omni-digital   File: test_forms.py    MIT License 5 votes vote down vote up
def test_form_inheritance(self):
        """Test form inheritance"""
        self.assertIsInstance(self.instance, forms.ModelForm) 
Example 77
Project: ops22   Author: spark8103   File: edit.py    MIT License 5 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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 class %s.'
                             % (e, self.__class__.__name__)) 
Example 78
Project: liberator   Author: libscie   File: options.py    Creative Commons Zero v1.0 Universal 4 votes vote down vote up
def get_form(self, request, obj=None, **kwargs):
        """
        Returns a Form class for use in the admin add view. This is used by
        add_view and change_view.
        """
        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:
            # 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 pass None to be consistent with the
        # default on modelform_factory
        exclude = exclude or None

        # Remove declared form fields which are in readonly_fields.
        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'] = forms.ALL_FIELDS

        try:
            return modelform_factory(self.model, **defaults)
        except FieldError as e:
            raise FieldError(
                '%s. Check fields/fieldsets/exclude attributes of class %s.'
                % (e, self.__class__.__name__)
            ) 
Example 79
Project: banruo   Author: yingshang   File: options.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def get_form(self, request, obj=None, change=False, **kwargs):
        """
        Return a Form class for use in the admin add view. This is used by
        add_view and change_view.
        """
        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)
        # Exclude all fields if it's a change form and the user doesn't have
        # the change permission.
        if change and hasattr(request, 'user') and not self.has_change_permission(request, obj):
            exclude.extend(fields)
        if excluded 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 pass None to be consistent with the
        # default on modelform_factory
        exclude = exclude or None

        # Remove declared form fields which are in readonly_fields.
        new_attrs = OrderedDict.fromkeys(
            f 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),
            **kwargs,
        }

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

        try:
            return modelform_factory(self.model, **defaults)
        except FieldError as e:
            raise FieldError(
                '%s. Check fields/fieldsets/exclude attributes of class %s.'
                % (e, self.__class__.__name__)
            ) 
Example 80
Project: code-inspector   Author: maxim5   File: 92590602231e23a755ecf47abf85b013_options.py    Apache License 2.0 4 votes vote down vote up
def get_form(self, request, obj=None, **kwargs):
        """
        Return a Form class for use in the admin add view. This is used by
        add_view and change_view.
        """
        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:
            # 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 pass None to be consistent with the
        # default on modelform_factory
        exclude = exclude or None

        # Remove declared form fields which are in readonly_fields.
        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'] = forms.ALL_FIELDS

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