我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.models.modelform_factory()。
def get_media_form(model): fields = model.admin_form_fields if 'collection' not in fields: # force addition of the 'collection' field, because leaving it out can # cause dubious results when multiple collections exist (e.g adding the # media to the root collection where the user may not have permission) - # and when only one collection exists, it will get hidden anyway. fields = list(fields) + ['collection'] return modelform_factory( model, form=BaseMediaForm, fields=fields, widgets={ 'tags': widgets.AdminTagWidget, 'file': forms.FileInput(), 'thumbnail': forms.ClearableFileInput(), })
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)
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
def get(self, request, object_id): model_fields = [f.name for f in self.opts.fields] fields = [f for f in request.GET['fields'].split(',') if f in model_fields] defaults = { "form": self.form, "fields": fields, "formfield_callback": self.formfield_for_dbfield, } form_class = modelform_factory(self.model, **defaults) form = form_class(instance=self.org_obj) helper = FormHelper() helper.form_tag = False helper.include_media = False form.helper = helper s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \ '<button type="submit" 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))
def post(self, request, object_id): model_fields = [f.name for f in self.opts.fields] fields = [f for f in request.POST.keys() if f in model_fields] defaults = { "form": self.form, "fields": fields, "formfield_callback": self.formfield_for_dbfield, } form_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)
def test_external_form_validation(self): """Test external plugin validation a bit""" form_class = modelform_factory( External, form=ExternalForm, fields='__all__', ) # Should not crash if URL not provided (765a6b6b53e) form = form_class({}) self.assertFalse(form.is_valid()) # Provide an invalid URL form = form_class({'url': 'http://192.168.250.1:65530'}) self.assertFalse(form.is_valid()) self.assertIn( '<li>Unable to fetch HTML for this URL, sorry!</li>', '%s' % form.errors)
def get_video_form(model): fields = model.admin_form_fields if 'collection' not in fields: # force addition of the 'collection' field, because leaving it out can # cause dubious results when multiple collections exist (e.g adding the # document to the root collection where the user may not have permission) - # and when only one collection exists, it will get hidden anyway. print('collection not found') fields = list(fields) + ['collection'] return modelform_factory( model, form=BaseVideoForm, fields=fields, formfield_callback=formfield_for_dbfield, # set the 'file' widget to a FileInput rather than the default ClearableFileInput # so that when editing, we don't get the 'currently: ...' banner which is # a bit pointless here widgets={ 'tags': widgets.AdminTagWidget, 'file': forms.FileInput(), 'thumbnail': forms.FileInput(), })
def get_model_form(self, **kwargs): """ ?? Model ?? Form ????????? """ 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: # ?? :attr:`~xadmin.views.base.ModelAdminView.exclude` ? None??? form ? Meta.exclude ???? # ??? form ? Meta.exclude exclude.extend(self.form._meta.exclude) # ?? exclude ?????????? None #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) # ?? modelform_factory ?? Form ? return modelform_factory(self.model, **defaults)
def get_model_form(self, **kwargs): """ ?? Model ?? Form ????????? """ 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: # ?? :attr:`~xadmin.views.base.ModelAdminView.exclude` ? None??? form ? Meta.exclude ???? # ??? form ? Meta.exclude exclude.extend(self.form._meta.exclude) # ?? exclude ?????????? None #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)
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))
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)
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)
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
def get(self, request, object_id): model_fields = [f.name for f in self.opts.fields] fields = [f for f in request.GET['fields'].split(',') if f in model_fields] defaults = { "form": self.form, "fields": fields, "formfield_callback": self.formfield_for_dbfield, } form_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 = {'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)} return HttpResponse(t.render(c))
def post(self, request, object_id): model_fields = [f.name for f in self.opts.fields] fields = [f for f in list(request.POST.keys()) if f in model_fields] defaults = { "form": self.form, "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)
def get_form_class(self, name): """ Returns the form class to be used with the named form. """ fields = self._get_from_name(name, 'fields') form_class = self._get_from_name(name, 'form_class') model = self._get_from_name(name, 'model') if fields is not None and form_class: raise ImproperlyConfigured( "Specifying both 'fields' and 'form_class' is not permitted." ) if form_class: return form_class elif model is not None: if fields is None: raise ImproperlyConfigured( "Using MultiModelFormMixin (base class of %s) without " "the 'fields' attribute is prohibited." % self.__class__.__name__ ) return model_forms.modelform_factory(model, fields=fields)