我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.utils.ErrorList()。
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, instance=None, use_required_attribute=None): opts = self._meta if opts.model is None: raise ValueError('ModelForm has no model class specified.') if instance is None: # if we didn't get an instance, instantiate a new one self.instance = opts.model() object_data = {} else: self.instance = instance object_data = model_to_dict(instance, opts.fields, opts.exclude) # if initial was provided, it should override the values from instance if initial is not None: object_data.update(initial) # self._validate_unique will be set to True by BaseModelForm.clean(). # It is False by default so overriding self.clean() and failing to call # super will stop validate_unique from being called. self._validate_unique = False super(BaseModelForm, self).__init__( data, files, auto_id, prefix, object_data, error_class, label_suffix, empty_permitted, use_required_attribute=use_required_attribute, )
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False): self.is_bound = data is not None or files is not None self.data = data or {} self.files = files or {} self.auto_id = auto_id self.prefix = prefix self.initial = initial or {} self.error_class = error_class # Translators: This is the default suffix added to form field labels self.label_suffix = label_suffix if label_suffix is not None else _(':') self.empty_permitted = empty_permitted self._errors = None # Stores the errors after clean() has been called. self._changed_data = None # The base_fields class attribute is the *class-wide* definition of # fields. Because a particular *instance* of the class might want to # alter self.fields, we create self.fields here by copying base_fields. # Instances should always modify self.fields; they should not modify # self.base_fields. self.fields = copy.deepcopy(self.base_fields) self._bound_fields_cache = {}
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=':', empty_permitted=False, instance=None): if instance: initial = initial or {} initial.update(self.populate_initials(instance)) super(PageUserForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance) if instance: # if it is a change form, keep those fields as not required # password will be changed only if there is something entered inside self.fields['password1'].required = False self.fields['password1'].label = _('New password') self.fields['password2'].required = False self.fields['password2'].label = _('New password confirmation') self._password_change = True
def form_valid(self, form): if self.__pk: obj = PurchasesInvoice.objects.get(pk=self.__pk) self.request.invoice = obj form.instance.invoice = obj # comprueba si el producto comprado requiere un valor de atributo especial product_final = ProductFinal.objects.filter(pk=form.data['product']).first() if not product_final: errors = form._errors.setdefault("feature_special_value", ErrorList()) errors.append(_("Product not selected")) return super(LineInvoiceCreate, self).form_invalid(form) elif product_final.product.feature_special: if 'feature_special_value' not in form.data or not form.data['feature_special_value']: errors = form._errors.setdefault("feature_special_value", ErrorList()) errors.append(_("Product needs information of feature special")) return super(LineInvoiceCreate, self).form_invalid(form) return super(LineInvoiceCreate, self).form_valid(form)
def form_valid(self, form): # validate quantity line_order = form.instance.line_order quantity = form.instance.quantity quantity_bd = SalesLineAlbaran.objects.filter(line_order=line_order).aggregate(q=Sum('quantity')) units_pending = line_order.quantity if quantity_bd['q']: quantity += quantity_bd['q'] units_pending -= quantity_bd['q'] if line_order.quantity < quantity: errors = form._errors.setdefault("quantity", ErrorList()) errors.append(_("La cantidad seleccionada es excesiva. Quedan pendiente {} unidades por albaranar".format(units_pending))) return super(LineAlbaranCreate, self).form_invalid(form) # initial albaran if self.__pk: obj = SalesAlbaran.objects.get(pk=self.__pk) self.request.albaran = obj form.instance.albaran = obj return super(LineAlbaranCreate, self).form_valid(form)
def form_valid(self, form): # validate quantity line_order = form.instance.line_order quantity = form.instance.quantity quantity_ticket = line_order.line_ticket_sales.annotate(q=Sum('quantity')).values_list('q') quantity_invoice = line_order.line_invoice_sales.annotate(q=Sum('quantity')).values_list('q') quantity_bd = 0 if quantity_ticket: quantity_bd += quantity_ticket[0][0] if quantity_invoice: quantity_bd += quantity_invoice[0][0] units_pending = line_order.quantity - quantity_bd if line_order.quantity < quantity: errors = form._errors.setdefault("quantity", ErrorList()) errors.append(_("La cantidad seleccionada es excesiva. Quedan pendiente {} unidades por crear ticket o factura".format(units_pending))) return super(LineTicketUpdate, self).form_invalid(form)
def form_valid(self, form): line_ticket = form.instance.line_ticket # sumatorio de las cantidades ya devueltas de la misma linea quantity_tmp = SalesLineTicketRectification.objects.filter( line_ticket=line_ticket ).annotate( q=Sum('quantity') ).values('q') if quantity_tmp: quantity_bd = line_ticket.quantity - quantity_tmp[0]['q'] else: quantity_bd = line_ticket.quantity # comprobamos que la cantidad correcta if quantity_bd < form.instance.quantity: errors = form._errors.setdefault("quantity", ErrorList()) errors.append(_("La cantidad seleccionada es excesiva. Las unidades maximas a devolver son {}".format(quantity_bd))) return super(LineTicketRectificationCreateModal, self).form_invalid(form) # initial ticket rectification if self.__pk: ticket_rectification = SalesTicketRectification.objects.get(pk=self.__pk) self.request.ticket_rectification = ticket_rectification form.instance.ticket_rectification = ticket_rectification return super(LineTicketRectificationCreateModal, self).form_valid(form)
def form_valid(self, form): line_ticket = form.instance.line_ticket # sumatorio de las cantidades ya devueltas de la misma linea salvo al actual quantity_tmp = SalesLineTicketRectification.objects.filter( line_ticket=line_ticket ).exclude( pk=form.initial.get("id") ).annotate( q=Sum('quantity') ).values('q') if quantity_tmp: quantity_bd = line_ticket.quantity - quantity_tmp[0]['q'] else: quantity_bd = line_ticket.quantity # comprobamos que la cantidad correcta if quantity_bd < form.instance.quantity: errors = form._errors.setdefault("quantity", ErrorList()) errors.append(_("La cantidad seleccionada es excesiva. Las unidades maximas a devolver son {}".format(quantity_bd))) return super(LineTicketRectificationUpdate, self).form_invalid(form) return super(LineTicketRectificationUpdate, self).form_valid(form)
def form_valid(self, form): # validate quantity line_order = form.instance.line_order quantity = form.instance.quantity quantity_invoice = line_order.line_invoice_sales.annotate(q=Sum('quantity')).values_list('q') quantity_bd = 0 if quantity_invoice: quantity_bd += quantity_invoice[0][0] units_pending = line_order.quantity - quantity_bd if line_order.quantity < quantity: errors = form._errors.setdefault("quantity", ErrorList()) errors.append(_("La cantidad seleccionada es excesiva. Quedan pendiente {} unidades por facturar".format(units_pending))) return super(LineInvoiceCreate, self).form_invalid(form) # initial invoice if self.__pk: obj = SalesInvoice.objects.get(pk=self.__pk) self.request.invoice = obj form.instance.invoice = obj return super(LineInvoiceCreate, self).form_valid(form)
def form_valid(self, form): # validate quantity line_order = form.instance.line_order quantity = form.instance.quantity quantity_invoice = line_order.line_invoice_sales.annotate(q=Sum('quantity')).values_list('q') quantity_bd = 0 if quantity_invoice: quantity_bd += quantity_invoice[0][0] units_pending = line_order.quantity - quantity_bd if line_order.quantity < quantity: errors = form._errors.setdefault("quantity", ErrorList()) errors.append(_("La cantidad seleccionada es excesiva. Quedan pendiente {} unidades por facturar".format(units_pending))) return super(LineInvoiceUpdate, self).form_invalid(form) return super(LineInvoiceUpdate, self).form_valid(form)
def form_valid(self, form): # raise Exception(form.initial) line_invoice = form.instance.line_invoice # sumatorio de las cantidades ya devueltas de la misma linea salvo al actual quantity_tmp = SalesLineInvoiceRectification.objects.filter( line_invoice=line_invoice ).exclude( pk=form.initial.get("id") ).annotate( q=Sum('quantity') ).values('q') if quantity_tmp: quantity_bd = line_invoice.quantity - quantity_tmp[0]['q'] else: quantity_bd = line_invoice.quantity # comprobamos que la cantidad correcta if quantity_bd < form.instance.quantity: errors = form._errors.setdefault("quantity", ErrorList()) errors.append(_("La cantidad seleccionada es excesiva. Las unidades maximas a devolver son {}".format(quantity_bd))) return super(LineInvoiceRectificationUpdate, self).form_invalid(form) return super(LineInvoiceRectificationUpdate, self).form_valid(form)
def form_valid(self, form, forms): pass_to_final = form.cleaned_data.get('pass_to_final') if pass_to_final: try: with transaction.atomic(): result = super(ProductCreateCustom, self).form_valid(form, forms) self.object.pass_to_productfinal() except IntegrityError as e: errors = form._errors.setdefault("code", ErrorList()) errors.append(e) temp_forms = [tform[0] for tform in forms] return self.form_invalid(form, temp_forms, 1, 1) return result else: return super(ProductCreateCustom, self).form_valid(form, forms)
def form_valid(self, form): attribute = form.cleaned_data['attribute'] if attribute.type_value == TYPE_VALUE_BOOLEAN: value = int(form.cleaned_data['value_bool']) elif attribute.type_value == TYPE_VALUE_FREE: value = form.cleaned_data['value_free'] elif attribute.type_value == TYPE_VALUE_LIST: value = form.cleaned_data['value_list'] if not OptionValueAttribute.objects.filter( pk=value, group__attributes=attribute ).exists(): errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Option invalid')) return super(ProductFeatureCreate, self).form_invalid(form) else: value = None if value is None: errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Value invalid')) return super(ProductFeatureCreate, self).form_invalid(form) self.request.value = value form.instance.value = value if self.__product_pk: product = ProductFinal.objects.get(pk=self.__product_pk) self.request.product = product form.instance.product = product return super(ProductFinalAttributeCreate, self).form_valid(form)
def form_valid(self, form): attribute = form.cleaned_data['attribute'] if attribute.type_value == TYPE_VALUE_BOOLEAN: value = int(form.cleaned_data['value_bool']) elif attribute.type_value == TYPE_VALUE_FREE: value = form.cleaned_data['value_free'] elif attribute.type_value == TYPE_VALUE_LIST: value = form.cleaned_data['value_list'] if not OptionValueAttribute.objects.filter( pk=value, group__attributes=attribute ).exists(): errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Option invalid')) return super(ProductFinalAttributeUpdate, self).form_invalid(form) else: value = None if value is None: errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Value invalid')) return super(ProductFinalAttributeUpdate, self).form_invalid(form) self.request.value = value form.instance.value = value return super(ProductFinalAttributeUpdate, self).form_valid(form)
def form_valid(self, form): feature = form.cleaned_data['feature'] if feature.type_value == TYPE_VALUE_BOOLEAN: value = int(form.cleaned_data['value_bool']) elif feature.type_value == TYPE_VALUE_FREE: value = form.cleaned_data['value_free'] elif feature.type_value == TYPE_VALUE_LIST: value = form.cleaned_data['value_list'] if not OptionValueFeature.objects.filter( pk=value, group__features=feature ).exists(): errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Option invalid')) return super(ProductFeatureCreate, self).form_invalid(form) else: value = None if value is None: errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Value invalid')) return super(ProductFeatureCreate, self).form_invalid(form) self.request.value = value form.instance.value = value if self.__product_pk: product = Product.objects.get(pk=self.__product_pk) self.request.product = product form.instance.product = product return super(ProductFeatureCreate, self).form_valid(form)
def form_valid(self, form): feature = form.cleaned_data['feature'] if feature.type_value == TYPE_VALUE_BOOLEAN: value = int(form.cleaned_data['value_bool']) elif feature.type_value == TYPE_VALUE_FREE: value = form.cleaned_data['value_free'] elif feature.type_value == TYPE_VALUE_LIST: value = form.cleaned_data['value_list'] if not OptionValueFeature.objects.filter( pk=value, group__features=feature ).exists(): errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Option invalid')) return super(ProductFeatureUpdate, self).form_invalid(form) else: value = None if value is None: errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Value invalid')) return super(ProductFeatureUpdate, self).form_invalid(form) self.request.value = value form.instance.value = value return super(ProductFeatureUpdate, self).form_valid(form)
def form_valid(self, form): try: return super(ProductUniqueUpdate, self).form_valid(form) except ValidationError as e: errors = form._errors.setdefault("value", ErrorList()) errors.append(e) return super(ProductUniqueCreate, self).form_invalid(form) except IntegrityError: errors = form._errors.setdefault("value", ErrorList()) errors.append(_("Value existing")) return super(ProductUniqueUpdate, self).form_invalid(form)
def clean(self): cleaned_data = super(FeatureForm, self).clean() type_value = cleaned_data.get("type_value") list_value = cleaned_data.get("list_value") if type_value == TYPE_VALUES[2][0] and list_value is None: self._errors["type_value"] = ErrorList([_("Debe elegir un lista de valores")])
def clean(self): cleaned_data = super(AttributeForm, self).clean() type_value = cleaned_data.get("type_value") list_value = cleaned_data.get("list_value") if type_value == TYPE_VALUES[2][0] and list_value is None: self._errors["type_value"] = ErrorList([_("Debe elegir un lista de valores")])
def clean(self): cleaned_data = super(FeatureSpecialForm, self).clean() type_value = cleaned_data.get("type_value") list_value = cleaned_data.get("list_value") if type_value == TYPE_VALUES[2][0] and list_value is None: self._errors["type_value"] = ErrorList([_("Debe elegir un lista de valores")])
def clean(self): if self.cleaned_data['view_video'] and not self.cleaned_data['product_final'].product.url_video: msg = _("The select product haven't video url") self._errors["view_video"] = ErrorList([_(msg)])
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, form_kwargs=None): self.is_bound = data is not None or files is not None self.prefix = prefix or self.get_default_prefix() self.auto_id = auto_id self.data = data or {} self.files = files or {} self.initial = initial self.form_kwargs = form_kwargs or {} self.error_class = error_class self._errors = None self._non_form_errors = None
def non_form_errors(self): """ Returns an ErrorList of errors that aren't associated with a particular form -- i.e., from formset.clean(). Returns an empty ErrorList if there are none. """ if self._non_form_errors is None: self.full_clean() return self._non_form_errors
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, instance=None): opts = self._meta if opts.model is None: raise ValueError('ModelForm has no model class specified.') if instance is None: # if we didn't get an instance, instantiate a new one self.instance = opts.model() object_data = {} else: self.instance = instance object_data = model_to_dict(instance, opts.fields, opts.exclude) # if initial was provided, it should override the values from instance if initial is not None: object_data.update(initial) # self._validate_unique will be set to True by BaseModelForm.clean(). # It is False by default so overriding self.clean() and failing to call # super will stop validate_unique from being called. self._validate_unique = False super(BaseModelForm, self).__init__(data, files, auto_id, prefix, object_data, error_class, label_suffix, empty_permitted) # Apply ``limit_choices_to`` to each field. for field_name in self.fields: formfield = self.fields[field_name] if hasattr(formfield, 'queryset') and hasattr(formfield, 'get_limit_choices_to'): limit_choices_to = formfield.get_limit_choices_to() if limit_choices_to is not None: formfield.queryset = formfield.queryset.complex_filter(limit_choices_to)
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, instance=None, use_required_attribute=None): opts = self._meta if opts.model is None: raise ValueError('ModelForm has no model class specified.') if instance is None: # if we didn't get an instance, instantiate a new one self.instance = opts.model() object_data = {} else: self.instance = instance object_data = model_to_dict(instance, opts.fields, opts.exclude) # if initial was provided, it should override the values from instance if initial is not None: object_data.update(initial) # self._validate_unique will be set to True by BaseModelForm.clean(). # It is False by default so overriding self.clean() and failing to call # super will stop validate_unique from being called. self._validate_unique = False super(BaseModelForm, self).__init__( data, files, auto_id, prefix, object_data, error_class, label_suffix, empty_permitted, use_required_attribute=use_required_attribute, ) # Apply ``limit_choices_to`` to each field. for field_name in self.fields: formfield = self.fields[field_name] if hasattr(formfield, 'queryset') and hasattr(formfield, 'get_limit_choices_to'): limit_choices_to = formfield.get_limit_choices_to() if limit_choices_to is not None: formfield.queryset = formfield.queryset.complex_filter(limit_choices_to)
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=form_utils.ErrorList, label_suffix=None, empty_permitted=False, instance=None): super(CreateAgentForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance) self.has_instance = instance is not None
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList): self.is_bound = data is not None or files is not None self.prefix = prefix or self.get_default_prefix() self.auto_id = auto_id self.data = data or {} self.files = files or {} self.initial = initial self.error_class = error_class self._errors = None self._non_form_errors = None
def non_field_errors(self): """ Returns an ErrorList of errors that aren't associated with a particular field -- i.e., from Form.clean(). Returns an empty ErrorList if there are none. """ return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield'))
def errors(self): """ Returns an ErrorList for this field. Returns an empty ErrorList if there are none. """ return self.form.errors.get(self.name, self.form.error_class())