我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用django.forms.formsets.formset_factory()。
def get(self, request): """ Method used to render the view when form is not submitted. """ objects = self.get_objects() formset = None if len(objects) > 0: ObjectFormSet = formset_factory(self.form_model, extra=0) formset = ObjectFormSet(initial=objects) else: messages.info(request, 'No data to import.') return redirect(self.get_return_url()) return render(request, self.template, { 'formset': formset, 'obj_type': self.form_model._meta.model._meta.verbose_name, 'return_url': self.get_return_url(), })
def test_for_formset(self): TestFormSet = formset_factory(TestForm, extra=1) test_formset = TestFormSet() res = render_template_with_form( '{% bootstrap_formset formset show_label=False %}', {'formset': test_formset} ) self.assertIn('sr-only', res)
def modelformset_factory(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None): """ Returns a FormSet class for the given Django model class. """ meta = getattr(form, 'Meta', None) if meta is None: meta = type(str('Meta'), (object,), {}) if (getattr(meta, 'fields', fields) is None and getattr(meta, 'exclude', exclude) is None): raise ImproperlyConfigured( "Calling modelformset_factory without defining 'fields' or " "'exclude' explicitly is prohibited." ) form = modelform_factory(model, form=form, fields=fields, exclude=exclude, formfield_callback=formfield_callback, widgets=widgets, localized_fields=localized_fields, labels=labels, help_texts=help_texts, error_messages=error_messages, field_classes=field_classes) FormSet = formset_factory(form, formset, extra=extra, min_num=min_num, max_num=max_num, can_order=can_order, can_delete=can_delete, validate_min=validate_min, validate_max=validate_max) FormSet.model = model return FormSet # InlineFormSets #############################################################
def modelformset_factory(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None): """ Returns a FormSet class for the given Django model class. """ meta = getattr(form, 'Meta', None) if (getattr(meta, 'fields', fields) is None and getattr(meta, 'exclude', exclude) is None): raise ImproperlyConfigured( "Calling modelformset_factory without defining 'fields' or " "'exclude' explicitly is prohibited." ) form = modelform_factory(model, form=form, fields=fields, exclude=exclude, formfield_callback=formfield_callback, widgets=widgets, localized_fields=localized_fields, labels=labels, help_texts=help_texts, error_messages=error_messages, field_classes=field_classes) FormSet = formset_factory(form, formset, extra=extra, min_num=min_num, max_num=max_num, can_order=can_order, can_delete=can_delete, validate_min=validate_min, validate_max=validate_max) FormSet.model = model return FormSet # InlineFormSets #############################################################
def add_data(request, pk): shop = get_object_or_404(Shop, pk=pk, user=request.user) # Hack to supply additional argument to the AddProdutsShopForm AddProductsShopFormSet = formset_factory(AddProductsShopForm, formset=AddProductsShopBaseFormSet) AddProductsShopFormSet.form = staticmethod(curry(AddProductsShopForm, shop=shop)) formset = AddProductsShopFormSet(request.POST or None) if request.method == 'POST': # Set csv file, we later access it in clean method try: formset.csv_file = request.session.pop(AddProductsShopForm.CSV_FILE_NAME) formset.csv_file.shop = shop except KeyError: pass if formset.is_valid(): images = [] data_list = [] for form in formset: data_list.append(form.cleaned_data) try: images.append(request.session.pop('product_%d' % form.cleaned_data['order'])) except KeyError: pass response = shop.api.add_product_data(data_list, images) return HttpResponse(simplejson.dumps({'response': response, 'result': 'success'})) else: response = {} for form in formset: order = form.data[form.prefix + '-order'][0] for k, v in form.errors.items(): response['form-%s-%s' % (order, k)] = v return HttpResponse(simplejson.dumps({'response': response, 'result': 'error'})) return direct_to_template(request, template="partial/shop_add_products.html", extra_context={'formset': formset, 'shop': shop})
def modelformset_factory(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False): """ Returns a FormSet class for the given Django model class. """ meta = getattr(form, 'Meta', None) if meta is None: meta = type(str('Meta'), (object,), {}) if (getattr(meta, 'fields', fields) is None and getattr(meta, 'exclude', exclude) is None): raise ImproperlyConfigured( "Calling modelformset_factory without defining 'fields' or " "'exclude' explicitly is prohibited." ) form = modelform_factory(model, form=form, fields=fields, exclude=exclude, formfield_callback=formfield_callback, widgets=widgets, localized_fields=localized_fields, labels=labels, help_texts=help_texts, error_messages=error_messages) FormSet = formset_factory(form, formset, extra=extra, min_num=min_num, max_num=max_num, can_order=can_order, can_delete=can_delete, validate_min=validate_min, validate_max=validate_max) FormSet.model = model return FormSet # InlineFormSets #############################################################
def test_for_formset(self): TestFormSet = formset_factory(TestForm, extra=1) test_formset = TestFormSet() res = render_template_with_form( '{% bootstrap_formset formset show_label=False %}', {'formset': test_formset} ) self.assertIn('sr-only', res) # TODO change for the new icons # def test_button_with_icon(self): # res = render_template_with_form( # "{% bootstrap_button 'test' icon='info-sign' %}" # ) # self.assertEqual( # res.strip(), # '<button class="btn btn-default"><span class="glyphicon glyphicon-info-sign"></span> test</button>' # ) # res = render_template_with_form( # "{% bootstrap_button 'test' icon='info-sign' button_class='btn-primary' %}" # ) # self.assertEqual( # res.strip(), # '<button class="btn btn-primary"><span class="glyphicon glyphicon-info-sign"></span> test</button>' # ) # res = render_template_with_form( # "{% bootstrap_button 'test' icon='info-sign' button_type='submit' %}" # ) # self.assertEqual( # res.strip(), # '<button class="btn btn-default" type="submit"><span class="glyphicon glyphicon-info-sign"></span> test</button>'
def roa_create_multi_confirm(request): """This function is called when the user confirms the creation of a ROA request. It is responsible for updating the IRDB. """ conf = get_conf(request.user, request.session['handle']) log = request.META['wsgi.errors'] if request.method == 'POST': formset = formset_factory(forms.ROARequestConfirm, extra=0)(request.POST, request.FILES) if formset.is_valid(): for cleaned_data in formset.cleaned_data: asn = cleaned_data.get('asn') prefix = cleaned_data.get('prefix') rng = resource_range_ip.parse_str(prefix) max_prefixlen = cleaned_data.get('max_prefixlen') # Always create ROA requests with a single prefix. # https://trac.rpki.net/ticket/32 roa = models.ROARequest.objects.create(issuer=conf, asn=asn) v = 'IPv%d' % rng.version roa.prefixes.create(version=v, prefix=str(rng.min), prefixlen=rng.prefixlen(), max_prefixlen=max_prefixlen) Zookeeper(handle=conf.handle, logstream=log, disable_signal_handlers=True).run_rpkid_now() return redirect(dashboard) # What should happen when the submission form isn't valid? For now # just fall through and redirect back to the ROA creation form return http.HttpResponseRedirect(reverse(roa_create_multi))
def modelformset_factory(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None): """ Returns a FormSet class for the given Django model class. """ # modelform_factory will produce the same warning/error, but that will be # difficult to debug for code that needs upgrading, so we produce the # warning here too. This logic is reproducing logic inside # modelform_factory, but it can be removed once the deprecation cycle is # complete, since the validation exception will produce a helpful # stacktrace. meta = getattr(form, 'Meta', None) if meta is None: meta = type(str('Meta'), (object,), {}) if (getattr(meta, 'fields', fields) is None and getattr(meta, 'exclude', exclude) is None): warnings.warn("Calling modelformset_factory without defining 'fields' or " "'exclude' explicitly is deprecated", PendingDeprecationWarning, stacklevel=2) form = modelform_factory(model, form=form, fields=fields, exclude=exclude, formfield_callback=formfield_callback, widgets=widgets, localized_fields=localized_fields, labels=labels, help_texts=help_texts, error_messages=error_messages) FormSet = formset_factory(form, formset, extra=extra, max_num=max_num, can_order=can_order, can_delete=can_delete, validate_max=validate_max) FormSet.model = model return FormSet # InlineFormSets #############################################################
def test_for_formset(self): TestFormSet = formset_factory(TestForm, extra=1) test_formset = TestFormSet() res = self.render_template_with_form( '{% propeller_formset formset show_label=False %}', {'formset': test_formset} ) self.assertIn('sr-only', res)
def post(self, request): """ The form has been submitted, process it. """ ObjectFormSet = formset_factory(self.form_model, extra=0) formset = ObjectFormSet(request.POST) new_objects = [] if formset.is_valid(): for form in formset: if form.is_valid(): instance = form.save() new_objects.append(instance) if new_objects: # Notify user of successful import message = 'Imported {} {}'.format( len(new_objects), new_objects[0]._meta.verbose_name_plural) messages.success(request, message) # Log the import action UserAction.objects.log_import(request.user, ContentType.objects.get_for_model( self.form_model._meta.model), message) return redirect(self.get_return_url()) formset = ObjectFormSet() return render(request, self.template, { 'formset': formset, 'obj_type': self.form_model._meta.model._meta.verbose_name, 'return_url': self.get_return_url(), })