我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用django.forms.formsets.BaseFormSet()。
def patch(): from django.forms import forms, formsets, util, widgets # Add __html__ methods to these classes: classes = [ forms.BaseForm, forms.BoundField, formsets.BaseFormSet, util.ErrorDict, util.ErrorList, widgets.Media, widgets.RadioFieldRenderer, ] try: classes.append(widgets.RadioChoiceInput) except AttributeError: classes.append(widgets.RadioInput) for cls in classes: if not hasattr(cls, '__html__'): cls.__html__ = __html__
def as_crispy_errors(form, template_pack=TEMPLATE_PACK): """ Renders only form errors the same way as django-crispy-forms:: {% load crispy_forms_tags %} {{ form|as_crispy_errors }} or:: {{ form|as_crispy_errors:"bootstrap" }} """ if isinstance(form, BaseFormSet): template = get_template('%s/errors_formset.html' % template_pack) c = Context({'formset': form}) else: template = get_template('%s/errors.html' % template_pack) c = Context({'form': form}) return template.render(c)
def __init__(self, *args, **kwargs): """ Filter our arguments that don't make sense for formsets as base_forms. Should be moved to multiforms itself. """ base_forms = self.get_base_forms() formset_names = [name for name, form in base_forms.items() if issubclass(form, formsets.BaseFormSet)] invalid_formset_kwargs = [ 'instance', 'empty_permitted', 'label_suffix' ] def filter_function(name, value): if name in formset_names: return multiform.InvalidArgument else: return value for kwarg in invalid_formset_kwargs: setattr(self, 'dispatch_init_{}'.format(kwarg), filter_function) return super().__init__(*args, **kwargs)
def _combine(self, *args, **kwargs): """ Combine with filter argument doesn't work for form sets. Because formsets will return always a list of values and even lists of falsy values are truthy. This extends combine to inside the lists returned by the formset and filter it if all values inside are false. WARNING: This kind of hacky. It should be better fixed somewhere else. """ base_forms = self.get_base_forms() values = super()._combine(*args, **kwargs) if 'filter' in kwargs and kwargs['filter']: values = OrderedDict([ (name, value) for name, value in values.items() if not issubclass(base_forms[name], formsets.BaseFormSet) or any(value) ]) return values
def __init__(self, formset, *args, **kwargs): if not isinstance(formset, BaseFormSet): raise BootstrapError( 'Parameter "formset" should contain a valid Django Formset.') self.formset = formset super(FormsetRenderer, self).__init__(*args, **kwargs)
def make_form_or_formset_fields_not_required(form_or_formset): """Take a Form or FormSet and set all fields to not required.""" if isinstance(form_or_formset, BaseFormSet): for single_form in form_or_formset: make_form_fields_not_required(single_form) else: make_form_fields_not_required(form_or_formset)
def as_crispy_form(form, template_pack=TEMPLATE_PACK, label_class="", field_class=""): """ The original and still very useful way to generate a div elegant form/formset:: {% load crispy_forms_tags %} <form class="uniForm" method="post"> {% csrf_token %} {{ myform|crispy }} </form> or, if you want to explicitly set the template pack:: {{ myform|crispy:"bootstrap" }} In ``bootstrap3`` for horizontal forms you can do:: {{ myform|label_class:"col-lg-2",field_class:"col-lg-8" }} """ if isinstance(form, BaseFormSet): template = uni_formset_template(template_pack) c = Context({ 'formset': form, 'form_show_errors': True, 'form_show_labels': True, 'label_class': label_class, 'field_class': field_class, }) else: template = uni_form_template(template_pack) c = Context({ 'form': form, 'form_show_errors': True, 'form_show_labels': True, 'label_class': label_class, 'field_class': field_class, }) return template.render(c)
def full_clean(self): """ Modified full clean that does collect cleaned data from formsets. Should be moved to multiforms itself. """ self._errors = self._combine('errors', filter=True) base_forms = self.get_base_forms() if not self._errors: self.cleaned_data = {} for name, formset in self.forms.items(): if issubclass(base_forms[name], formsets.BaseFormSet): self.cleaned_data[name] = [f.cleaned_data for f in formset]
def __init__(self, formset, *args, **kwargs): if not isinstance(formset, BaseFormSet): raise PropellerError( 'Parameter "formset" should contain a valid Django Formset.') self.formset = formset super(FormsetRenderer, self).__init__(*args, **kwargs)
def compute_form_list(cls, form_list, *args, **kwargs): computed_form_list = OrderedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. (step_name, form) = form if isinstance(form, dict): form_mapping = form computed_form_list[six.text_type(step_name)] = form_mapping elif isinstance(form, (list, tuple)): form_mapping = OrderedDict(form) computed_form_list[six.text_type(step_name)] = form_mapping elif issubclass(form, (forms.Form, forms.BaseForm, forms.BaseFormSet)): computed_form_list[six.text_type(step_name)] = form else: # if not, add the form with a zero based counter as unicode computed_form_list[six.text_type(i)] = form # walk through the new created list of forms for form in six.itervalues(computed_form_list): form_collection = [] if isinstance(form, dict): form_collection = form.values() elif issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form form_collection = [form] for form in form_collection: # must test for BaseFormSet again in case form_collection # is a dict containing one. if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet or # ModelFormSet) we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the wizardview (by subclassing). for field in six.itervalues(form.base_fields): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured( "You need to define 'file_storage' in your " "wizard view in order to handle file uploads.") return computed_form_list
def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the wizardview will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary whose values are model instances if the step is based on a ``ModelForm`` and querysets if the step is based on a ``ModelFormSet``. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the wizardview instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[six.text_type(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[six.text_type(i)] = form # walk through the new created list of forms for form in six.itervalues(init_form_list): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the wizardview (by subclassing). for field in six.itervalues(form.base_fields): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured( "You need to define 'file_storage' in your " "wizard view in order to handle file uploads.") # build the kwargs for the wizardview instances kwargs['form_list'] = init_form_list return kwargs
def get_render(self, context): """ Returns a `Context` object with all the necesarry stuff for rendering the form :param context: `django.template.Context` variable holding the context for the node `self.form` and `self.helper` are resolved into real Python objects resolving them from the `context`. The `actual_form` can be a form or a formset. If it's a formset `is_formset` is set to True. If the helper has a layout we use it, for rendering the form or the formset's forms. """ # Nodes are not thread safe in multithreaded environments # https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#thread-safety-considerations if self not in context.render_context: context.render_context[self] = ( template.Variable(self.form), template.Variable(self.helper) if self.helper else None ) form, helper = context.render_context[self] actual_form = form.resolve(context) if self.helper is not None: helper = helper.resolve(context) else: # If the user names the helper within the form `helper` (standard), we use it # This allows us to have simplified tag syntax: {% crispy form %} helper = FormHelper() if not hasattr(actual_form, 'helper') else actual_form.helper self.actual_helper = helper # We get the response dictionary is_formset = isinstance(actual_form, BaseFormSet) response_dict = self.get_response_dict(helper, context, is_formset) node_context = copy_context(context) node_context.update(response_dict) # If we have a helper's layout we use it, for the form or the formset's forms if helper and helper.layout: if not is_formset: actual_form.form_html = helper.render_layout(actual_form, node_context, template_pack=self.template_pack) else: forloop = ForLoopSimulator(actual_form) helper.render_hidden_fields = True for form in actual_form: node_context.update({'forloop': forloop}) form.form_html = helper.render_layout(form, node_context, template_pack=self.template_pack) forloop.iterate() if is_formset: response_dict.update({'formset': actual_form}) else: response_dict.update({'form': actual_form}) return Context(response_dict)