当前位置: 首页>>代码示例>>Python>>正文


Python forms.ModelForm方法代码示例

本文整理汇总了Python中django.forms.ModelForm方法的典型用法代码示例。如果您正苦于以下问题:Python forms.ModelForm方法的具体用法?Python forms.ModelForm怎么用?Python forms.ModelForm使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.forms的用法示例。


在下文中一共展示了forms.ModelForm方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_model_form

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
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) 
开发者ID:stormsha,项目名称:StormOnline,代码行数:25,代码来源:detail.py

示例2: get_step_form

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
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 
开发者ID:stormsha,项目名称:StormOnline,代码行数:22,代码来源:wizard.py

示例3: __init__

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
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?' 
开发者ID:certsocietegenerale,项目名称:FIR,代码行数:26,代码来源:forms.py

示例4: clean_device_name

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
def clean_device_name(self):
        if 'device_name' not in self.cleaned_data:
            raise forms.ValidationError("A device name must be specified")
        else:
            device_name = self.cleaned_data['device_name']

        # Name uniqueness is enforced on the sql CREATE, but since we're not using a ModelForm this form won't check to
        # see if the name is actually uniqye. That said - we only need to check if we're creating the object. We do not
        # need to check if we're modifying the object.
        if 'modify_not_create' not in self.cleaned_data:
            modify_not_create = False
        else:
            modify_not_create = self.cleaned_data['modify_not_create']

        if not modify_not_create:  # If we're creating, not modifying
            try:
                existing_device = BrewPiDevice.objects.get(device_name=device_name)
                raise forms.ValidationError("A device already exists with the name {}".format(device_name))

            except ObjectDoesNotExist:
                # There was no existing device - we're good.
                return device_name
        else:
            # For modifications, we always return the device name
            return device_name 
开发者ID:thorrak,项目名称:fermentrack,代码行数:27,代码来源:device_forms.py

示例5: get_modelinstance_form

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
def get_modelinstance_form(metadata_class):
    model_class = metadata_class._meta.get_model('modelinstance')

    # Restrict content type choices to the models set in seo_models
    content_types = get_seo_content_types(metadata_class._meta.seo_models)

    # Get a list of fields, with _content_type at the start
    important_fields = ['_content_type'] + ['_object_id'] + core_choice_fields(metadata_class)
    _fields = important_fields + list(fields_for_model(model_class,
                                                  exclude=important_fields).keys())

    class ModelMetadataForm(forms.ModelForm):
        _content_type = forms.ModelChoiceField(
            queryset=ContentType.objects.filter(id__in=content_types),
            empty_label=None,
            label=capfirst(_("model")),
        )

        _object_id = forms.IntegerField(label=capfirst(_("ID")))

        class Meta:
            model = model_class
            fields = _fields

    return ModelMetadataForm 
开发者ID:whyflyru,项目名称:django-seo,代码行数:27,代码来源:admin.py

示例6: get_view_form

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
def get_view_form(metadata_class):
    model_class = metadata_class._meta.get_model('view')

    # Restrict content type choices to the models set in seo_models
    view_choices = [(key, " ".join(key.split("_"))) for key in get_seo_views(metadata_class)]
    view_choices.insert(0, ("", "---------"))

    # Get a list of fields, with _view at the start
    important_fields = ['_view'] + core_choice_fields(metadata_class)
    _fields = important_fields + list(fields_for_model(model_class,
                                                  exclude=important_fields).keys())

    class ModelMetadataForm(forms.ModelForm):
        _view = forms.ChoiceField(label=capfirst(_("view")),
                                  choices=view_choices, required=False)

        class Meta:
            model = model_class
            fields = _fields

    return ModelMetadataForm 
开发者ID:whyflyru,项目名称:django-seo,代码行数:23,代码来源:admin.py

示例7: __init__

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['emri'].widget.attrs.update({'class': 'form-control'})

            

# class LendetForm(forms.ModelForm):

#     class Meta:
#         model = ProvimetMundshme
#         fields = '__all__'

#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         self.fields['program'].widget.attrs.update({'class': 'form-control', 'data-type': 'program-listener'})
#         self.fields['semester'].widget.attrs.update({'class': 'form-control'})
#         self.fields['year'].widget.attrs.update({'class': 'form-control'})
#         self.fields['level'].widget.attrs.update({'class': 'form-control'})

#     course = forms.MultipleChoiceField(
#         widget=forms.CheckboxSelectMultiple,
#         choices=[(c.pk, c.name) for c in Course.objects.all()],
#     ) 
开发者ID:urankajtazaj,项目名称:SEMS,代码行数:25,代码来源:forms.py

示例8: test_cms_plugins_organization_form_page_choices

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
def test_cms_plugins_organization_form_page_choices(self):
        """
        The form to create a organization plugin should only list organization pages
        in the select box. There shouldn't be any duplicate because of published status.
        """

        class OrganizationPluginModelForm(forms.ModelForm):
            """A form for testing the choices in the select box"""

            class Meta:
                model = OrganizationPluginModel
                fields = ["page"]

        organization = OrganizationFactory(should_publish=True)
        other_page_title = "other page"
        create_page(
            other_page_title, "richie/single_column.html", settings.LANGUAGE_CODE
        )
        plugin_form = OrganizationPluginModelForm()
        rendered_form = plugin_form.as_table()
        self.assertEqual(
            rendered_form.count(organization.extended_object.get_title()), 1
        )
        self.assertNotIn(other_page_title, plugin_form.as_table()) 
开发者ID:openfun,项目名称:richie,代码行数:26,代码来源:test_cms_plugins_organization.py

示例9: test_cms_plugins_person_form_page_choices

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
def test_cms_plugins_person_form_page_choices(self):
        """
        The form to create a person plugin should only list person pages in the select box.
        """

        class PersonPluginModelForm(forms.ModelForm):
            """A form for testing the choices in the select box"""

            class Meta:
                model = PersonPluginModel
                fields = ["page"]

        person = PersonFactory()
        other_page_title = "other page"
        create_page(
            other_page_title, "richie/single_column.html", settings.LANGUAGE_CODE
        )
        plugin_form = PersonPluginModelForm()
        self.assertIn(person.extended_object.get_title(), plugin_form.as_table())
        self.assertNotIn(other_page_title, plugin_form.as_table()) 
开发者ID:openfun,项目名称:richie,代码行数:22,代码来源:test_cms_plugins_person.py

示例10: test_cms_plugins_blogpost_form_page_choices

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
def test_cms_plugins_blogpost_form_page_choices(self):
        """
        The form to create a blogpost plugin should only list blogpost pages
        in the select box.
        """

        class BlogPostPluginModelForm(forms.ModelForm):
            """A form for testing the choices in the select box"""

            class Meta:
                model = BlogPostPluginModel
                fields = ["page"]

        blog_page = create_i18n_page("my title", published=True)
        blogpost = BlogPostFactory(page_parent=blog_page)
        other_page_title = "other page"
        create_page(
            other_page_title, "richie/single_column.html", settings.LANGUAGE_CODE
        )
        plugin_form = BlogPostPluginModelForm()
        rendered_form = plugin_form.as_table()
        self.assertEqual(rendered_form.count(blogpost.extended_object.get_title()), 1)
        self.assertNotIn(other_page_title, plugin_form.as_table()) 
开发者ID:openfun,项目名称:richie,代码行数:25,代码来源:test_cms_plugins_blogpost.py

示例11: test_cms_plugins_organizations_by_category_form_page_choices

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
def test_cms_plugins_organizations_by_category_form_page_choices(self):
        """
        The form to create an organizations by category plugin should only list category pages
        in the select box. There shouldn't be any duplicate because of published status.
        """

        class OrganizationsByCategoryPluginModelForm(forms.ModelForm):
            """A form for testing the choices in the select box"""

            class Meta:
                model = OrganizationsByCategoryPluginModel
                fields = ["page"]

        category = CategoryFactory(should_publish=True)
        PageFactory(title__title="other page", should_publish=True)

        plugin_form = OrganizationsByCategoryPluginModelForm()
        rendered_form = plugin_form.as_table()

        self.assertEqual(rendered_form.count(category.extended_object.get_title()), 1)
        self.assertNotIn("other", plugin_form.as_table()) 
开发者ID:openfun,项目名称:richie,代码行数:23,代码来源:test_cms_plugins_organizations_by_category.py

示例12: test_cms_plugins_program_form_page_choices

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
def test_cms_plugins_program_form_page_choices(self):
        """
        The form to create a program plugin should only list program pages
        in the select box.
        """

        class ProgramPluginModelForm(forms.ModelForm):
            """A form for testing the choices in the select box"""

            class Meta:
                model = ProgramPluginModel
                fields = ["page"]

        program_page = create_i18n_page("my title", published=True)
        program = ProgramFactory(page_parent=program_page)
        other_page_title = "other page"
        create_page(
            other_page_title, "richie/single_column.html", settings.LANGUAGE_CODE
        )
        plugin_form = ProgramPluginModelForm()
        rendered_form = plugin_form.as_table()
        self.assertEqual(rendered_form.count(program.extended_object.get_title()), 1)
        self.assertNotIn(other_page_title, plugin_form.as_table()) 
开发者ID:openfun,项目名称:richie,代码行数:25,代码来源:test_cms_plugins_program.py

示例13: __init__

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
def __init__(self, instance, *args, **kwargs):
        """Overrides forms.ModelForm.__init__()
        Unlike forms.ModelForm, instance is required
        """
        self.attrs = kwargs.pop('attrs', {})
        self.use_react = kwargs.pop('use_react', False)
        self.instance = instance
        self._save_fields_lookup = kwargs.pop('save_fields_lookup', {})

        super(AbstractModelInstanceUpdateForm, self).__init__(instance=instance, *args, **kwargs)
        self._set_save_fields(*args)

        if args or kwargs:
            # make all non-save fields optional
            for name, field in self.fields.items():
                if name not in self._save_fields_lookup:
                    field.required = False
                else:
                    pass
        else:
            # leave the fields the way they are for rendering a form initially
            pass
        set_input_attrs(self)
        set_input_placeholder_labels(self) 
开发者ID:hacktoolkit,项目名称:django-htk,代码行数:26,代码来源:classes.py

示例14: get_model_form

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
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) 
开发者ID:madre,项目名称:devops,代码行数:25,代码来源:detail.py

示例15: get_form_model_verbose_name

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import ModelForm [as 别名]
def get_form_model_verbose_name(instance):
    if isinstance(instance, ModelForm):
        return instance._meta.model._meta.verbose_name.title()
    if isinstance(instance, BaseFormSet):
        return instance.model._meta.verbose_name_plural.title()
    return '<unknown>' 
开发者ID:dulacp,项目名称:django-accounting,代码行数:8,代码来源:introspection_filters.py


注:本文中的django.forms.ModelForm方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。