Python django.forms 模块,ModelForm() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.ModelForm()

项目:fir_async_plugin    作者:gcrahay    | 项目源码 | 文件源码
def preferences(request):

    class NotificationPreferenceForm(forms.ModelForm):
        event = forms.ChoiceField(choices=registry.get_event_choices(), disabled=True, widget=forms.HiddenInput())
        method = forms.ChoiceField(choices=registry.get_method_choices(), disabled=True, widget=forms.HiddenInput())
        business_lines = forms.ModelMultipleChoiceField(BusinessLine.authorization.for_user(request.user,
                                                                                            'incidents.view_incidents'),
                                                        required=False)

        class Meta:
            fields = "__all__"

    formset = forms.inlineformset_factory(User, NotificationPreference,
                                          formset=NotificationPreferenceFormset,
                                          form=NotificationPreferenceForm)
    if request.method == 'POST':
        fs = formset(request.POST, instance=request.user)
        if fs.is_valid():
            fs.save()
        return redirect('user:profile')
    else:
        fs = formset(instance=request.user)

    return render(request, "fir_async/preferences.html", {'formset': fs})
项目:djangoStatusPanel    作者:okar1    | 项目源码 | 文件源码
def save(self, commit=True):
        # Get the unsave Pizza instance
        instance = forms.ModelForm.save(self, False)

        # Prepare a 'save_m2m' method for the form,
        old_save_m2m = self.save_m2m
        def save_m2m():
            old_save_m2m()
            # This is where we actually link the pizza with toppings
            instance.tasksets_set.clear()
            for item in self.cleaned_data['taskSets']:
                instance.tasksets_set.add(item)
        self.save_m2m = save_m2m

        # Do we need to save all changes now?
        if commit:
            instance.save()
            self.save_m2m()
        return instance


# custom form for hosts
# adds ability to select linked taskSets
项目:djangoStatusPanel    作者:okar1    | 项目源码 | 文件源码
def save(self, commit=True):
        # Get the unsave Pizza instance
        instance = forms.ModelForm.save(self, False)

        # Prepare a 'save_m2m' method for the form,
        old_save_m2m = self.save_m2m
        def save_m2m():
            old_save_m2m()
            # This is where we actually link the pizza with toppings
            instance.boxes_set.clear()
            for item in self.cleaned_data['boxes']:
                instance.boxes_set.add(item)
        self.save_m2m = save_m2m

        # Do we need to save all changes now?
        if commit:
            instance.save()
            self.save_m2m()

        return instance
项目:blog_django    作者:chnpmy    | 项目源码 | 文件源码
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)
项目:blog_django    作者:chnpmy    | 项目源码 | 文件源码
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
项目:dream_blog    作者:fanlion    | 项目源码 | 文件源码
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)
项目:dream_blog    作者:fanlion    | 项目源码 | 文件源码
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
项目:MxOnline    作者:myTeemo    | 项目源码 | 文件源码
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)
项目:MxOnline    作者:myTeemo    | 项目源码 | 文件源码
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
项目:djangoblog    作者:liuhuipy    | 项目源码 | 文件源码
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)
项目:djangoblog    作者:liuhuipy    | 项目源码 | 文件源码
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
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
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)
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
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
项目:xadmin-markdown-editor    作者:bluenknight    | 项目源码 | 文件源码
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)
项目:xadmin-markdown-editor    作者:bluenknight    | 项目源码 | 文件源码
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
项目:gitmate-2    作者:GitMateIO    | 项目源码 | 文件源码
def __new__(cls, clsname, bases, attrs):
        # making sure we are using the correct class
        if len(bases) < 1:  # pragma: no cover
            raise ValueError('SettingsBaseAdminForm requires a base class')
        assert issubclass(bases[0], SettingsBase)

        meta = type('SettingsBaseAdminModelFormMeta',
                    (object, ),
                    {'model': bases[0], 'fields': '__all__'})
        class_dict = {'Meta': meta}

        # add user overrides, if specified
        class_dict.update(attrs)
        model_form = type(
            bases[0].__name__ + 'ModelForm',
            (_SettingsBaseModelFormTemplate, ),
            class_dict)
        return model_form
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
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
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
        defaults = {
            "form": forms.ModelForm,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(instance=self.org_obj)

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

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

        return HttpResponse(t.render(c))
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
def post(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.POST.keys() if f in model_fields]
        defaults = {
            "form": forms.ModelForm,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(
            instance=self.org_obj, data=request.POST, files=request.FILES)

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

        return self.render_response(result)
项目:eduDjango    作者:yuzhou6    | 项目源码 | 文件源码
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)
项目:eduDjango    作者:yuzhou6    | 项目源码 | 文件源码
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
项目:Django-IMOOC-Shop    作者:LBruse    | 项目源码 | 文件源码
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)
项目:Django-IMOOC-Shop    作者:LBruse    | 项目源码 | 文件源码
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
项目:StudyOnline    作者:yipwinghong    | 项目源码 | 文件源码
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)
项目:StudyOnline    作者:yipwinghong    | 项目源码 | 文件源码
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
项目:xadmin_python3    作者:mahongquan    | 项目源码 | 文件源码
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)
项目:xadmin_python3    作者:mahongquan    | 项目源码 | 文件源码
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 isinstance(callback, collections.Callable):
                    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
项目:Django-shop    作者:poetries    | 项目源码 | 文件源码
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)
项目:Django-shop    作者:poetries    | 项目源码 | 文件源码
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
项目:RPKI-toolkit    作者:pavel-odintsov    | 项目源码 | 文件源码
def ChildForm(instance):
    """
    Form for editing a Child model.

    This is roughly based on the equivalent ModelForm, but uses Form as a base
    class so that selection boxes for the AS and Prefixes can be edited in a
    single form.

    """

    class _wrapped(forms.Form):
        valid_until = forms.DateTimeField(initial=instance.valid_until)
        as_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildASN.objects.filter(child=instance),
                                                   required=False,
                                                   label='AS Ranges',
                                                   help_text='deselect to remove delegation')
        address_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildNet.objects.filter(child=instance),
                                                        required=False,
                                                        help_text='deselect to remove delegation')

    return _wrapped
项目:RPKI-toolkit    作者:pavel-odintsov    | 项目源码 | 文件源码
def ChildForm(instance):
    """
    Form for editing a Child model.

    This is roughly based on the equivalent ModelForm, but uses Form as a base
    class so that selection boxes for the AS and Prefixes can be edited in a
    single form.

    """

    class _wrapped(forms.Form):
        valid_until = forms.DateTimeField(initial=instance.valid_until)
        as_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildASN.objects.filter(child=instance),
                                                   required=False,
                                                   label='AS Ranges',
                                                   help_text='deselect to remove delegation')
        address_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildNet.objects.filter(child=instance),
                                                        required=False,
                                                        help_text='deselect to remove delegation')

    return _wrapped
项目:RPKI-toolkit    作者:pavel-odintsov    | 项目源码 | 文件源码
def ChildForm(instance):
    """
    Form for editing a Child model.

    This is roughly based on the equivalent ModelForm, but uses Form as a base
    class so that selection boxes for the AS and Prefixes can be edited in a
    single form.

    """

    class _wrapped(forms.Form):
        valid_until = forms.DateTimeField(initial=instance.valid_until)
        as_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildASN.objects.filter(child=instance),
                                                   required=False,
                                                   label='AS Ranges',
                                                   help_text='deselect to remove delegation')
        address_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildNet.objects.filter(child=instance),
                                                        required=False,
                                                        help_text='deselect to remove delegation')

    return _wrapped
项目:RPKI-toolkit    作者:pavel-odintsov    | 项目源码 | 文件源码
def ChildForm(instance):
    """
    Form for editing a Child model.

    This is roughly based on the equivalent ModelForm, but uses Form as a base
    class so that selection boxes for the AS and Prefixes can be edited in a
    single form.

    """

    class _wrapped(forms.Form):
        valid_until = forms.DateTimeField(initial=instance.valid_until)
        as_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildASN.objects.filter(child=instance),
                                                   required=False,
                                                   label='AS Ranges',
                                                   help_text='deselect to remove delegation')
        address_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildNet.objects.filter(child=instance),
                                                        required=False,
                                                        help_text='deselect to remove delegation')

    return _wrapped
项目:RPKI-toolkit    作者:pavel-odintsov    | 项目源码 | 文件源码
def ChildForm(instance):
    """
    Form for editing a Child model.

    This is roughly based on the equivalent ModelForm, but uses Form as a base
    class so that selection boxes for the AS and Prefixes can be edited in a
    single form.

    """

    class _wrapped(forms.Form):
        valid_until = forms.DateTimeField(initial=instance.valid_until)
        as_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildASN.objects.filter(child=instance),
                                                   required=False,
                                                   label='AS Ranges',
                                                   help_text='deselect to remove delegation')
        address_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildNet.objects.filter(child=instance),
                                                        required=False,
                                                        help_text='deselect to remove delegation')

    return _wrapped
项目:RPKI-toolkit    作者:pavel-odintsov    | 项目源码 | 文件源码
def ChildForm(instance):
    """
    Form for editing a Child model.

    This is roughly based on the equivalent ModelForm, but uses Form as a base
    class so that selection boxes for the AS and Prefixes can be edited in a
    single form.

    """

    class _wrapped(forms.Form):
        valid_until = forms.DateTimeField(initial=instance.valid_until)
        as_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildASN.objects.filter(child=instance),
                                                   required=False,
                                                   label='AS Ranges',
                                                   help_text='deselect to remove delegation')
        address_ranges = forms.ModelMultipleChoiceField(queryset=models.ChildNet.objects.filter(child=instance),
                                                        required=False,
                                                        help_text='deselect to remove delegation')

    return _wrapped
项目:MoocOnline    作者:My-captain    | 项目源码 | 文件源码
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)
项目:MoocOnline    作者:My-captain    | 项目源码 | 文件源码
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
项目:wger-lycan-clan    作者:andela    | 项目源码 | 文件源码
def get_form_class(self):
        '''
        The form can only show the workouts belonging to the user.

        This is defined here because only at this point during the request
        have we access to the current user
        '''

        class StepForm(ModelForm):
            workout = ModelChoiceField(queryset=Workout.objects.filter(user=self.request.user))

            class Meta:
                model = ScheduleStep
                exclude = ('order', 'schedule')

        return StepForm
项目:wger-lycan-clan    作者:andela    | 项目源码 | 文件源码
def get_form_class(self):
        '''
        The form can only show the workouts belonging to the user.

        This is defined here because only at this point during the request
        have we access to the current user
        '''

        class StepForm(ModelForm):
            workout = ModelChoiceField(queryset=Workout.objects.filter(user=self.request.user))

            class Meta:
                model = ScheduleStep
                exclude = ('order', 'schedule')

        return StepForm
项目:followme    作者:wzqnls    | 项目源码 | 文件源码
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)
项目:followme    作者:wzqnls    | 项目源码 | 文件源码
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
项目:mxonline    作者:huwei86    | 项目源码 | 文件源码
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)
项目:fakester    作者:pawelad    | 项目源码 | 文件源码
def test_from_inheritance(self, redirect_form):
        """Form should inherit from `django.forms.ModelForm`"""
        assert isinstance(redirect_form, forms.ModelForm)
项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def save(self, **kwargs):
        # ??? ?????? 'commit'? ?? ???
        commit = kwargs.get('commit', True)
        # ??? ?????? 'author'? ?? ????, ?? kwargs dict?? ??
        author = kwargs.pop('author', None)

        # self.instance.pk? ???? ???(?? ?????)
        # author? User????? ??
        # ? ??? ???? self.instance.author? ??? author?? ??(User?? None? ? ??)
        if not self.instance.pk or isinstance(author, User):
            self.instance.author = author
        # super()? save()??
        instance = super().save(**kwargs)

        # commit??? True?? comment??? ??? ?? ?? Comment?? ??? ??
        # ?? Comment? instance? my_comment??? ????
        #   (? ??? super().save()? ???? ???
        #       ??????? author? pk? ?? ??? ?? ??)
        comment_string = self.cleaned_data['comment']
        if commit and comment_string:
            # my_comment? ?? ?? ?? (update? ??)
            if instance.my_comment:
                instance.my_comment.content = comment_string
                instance.my_comment.save()
            # my_comment? ?? ??, Comment??? ???? my_comment OTO field? ??
            else:
                instance.my_comment = Comment.objects.create(
                    post=instance,
                    author=instance.author,
                    content=comment_string
                )
            # OTO??? ??? ?? Post? save()??
            instance.save()
        # ModelForm? save()?? ???? ?? model? instance??
        return instance
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
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.
        """
        r = form.save(commit=False)
        parent_id = request.GET.get('parent_id', None)
        if not parent_id:
            parent_id = request.POST.get('parent_id', None)
        if parent_id:
            parent = Folder.objects.get(id=parent_id)
            r.parent = parent
        return r
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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.remote_field.model != 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
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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.remote_field.model != 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
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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)