Ejemplo n.º 1
0
def validation_error_as_text(error):
    """
    Given a ValidationError object, return a string representing the errors.
    """
    try:
        ed = ErrorDict(error.message_dict)
        return ed.as_text()
    except AttributeError:
        el = ErrorList(error.messages)
        return el.as_text()
Ejemplo n.º 2
0
    def render(self, context):
        """Render."""
        form = self.form.resolve(context, True)

        hidden_fields_errors = ErrorDict()

        for field in form.hidden_fields():
            if field.errors:
                hidden_fields_errors.update({field.name: field.errors})

        context[self.as_var] = hidden_fields_errors
        return ''
Ejemplo n.º 3
0
 def _post_clean(self):
     """
     Rewrite the error dictionary, so that its keys correspond to the model fields.
     """
     super(NgModelFormMixin, self)._post_clean()
     if self._errors and self.prefix:
         self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._errors.items())
Ejemplo n.º 4
0
    def test_error_dict_copy(self):
        e = ErrorDict()
        e['__all__'] = ErrorList([
            ValidationError(
                message='message %(i)s',
                params={'i': 1},
            ),
            ValidationError(
                message='message %(i)s',
                params={'i': 2},
            ),
        ])

        e_copy = copy.copy(e)
        self.assertEqual(e, e_copy)
        self.assertEqual(e.as_data(), e_copy.as_data())

        e_deepcopy = copy.deepcopy(e)
        self.assertEqual(e, e_deepcopy)
Ejemplo n.º 5
0
def add_doctor(request):
    if request.user.is_authenticated and request.user.manager.role == "Manager":
        if request.POST:
            user_form = UserForm(request.POST)
            doctor_form = DoctorForm(request.POST)
            if user_form.is_valid() and doctor_form.is_valid():
                if int(request.POST["age"]) <= int(
                        request.POST["years_of_experience"]):
                    return render(
                        request, 'manager/add_doctor.html', {
                            'other_errors':
                            ErrorDict({
                                "Years of Experience":
                                ErrorDict({
                                    '':
                                    "Years of experience cannot be equal or greater than age"
                                })
                            })
                        })
                user = user_form.save(commit=False)
                password = request.POST["password"]
                try:
                    password_validation.validate_password(password)
                except Exception as e:
                    errAsDict = {
                        'password': ErrorDict({'': '\n'.join(e.messages)})
                    }
                    return render(request, 'manager/add_doctor.html',
                                  {'user_form_error': ErrorDict(errAsDict)})
                passwordConfirm = request.POST["passwordConfirm"]
                if password != passwordConfirm:
                    return render(
                        request, 'manager/add_doctor.html', {
                            'other_errors':
                            ErrorDict({
                                "Password":
                                ErrorDict({'': "Passwords do not match"})
                            })
                        })
                user.set_password(password)
                user.save()
                doctor = doctor_form.save(commit=False)
                doctor.user = user
                doctor.role = "Doctor"
                doctor.save()
                return redirect('/manager/get_report')
            else:
                return render(
                    request, 'manager/add_doctor.html', {
                        'user_form_error': user_form.errors,
                        'doctor_form_error': doctor_form.errors
                    })
        else:
            return render(request, 'manager/add_doctor.html')
    return redirect('/')
Ejemplo n.º 6
0
    def full_clean(self):
        """
        Clean all of self.data and populate self._errors and self.cleaned_data.
        """
        self._errors = ErrorDict()
        if not self.is_bound:  # Stop further processing.
            return
        self.cleaned_data = {}
        # If the form is permitted to be empty, and none of the form data has
        # changed from the initial data, short circuit any validation.
        if self.empty_permitted and not self.has_changed():
            return

        self._clean_fields()
        self._clean_form()
        self._post_clean()
Ejemplo n.º 7
0
    def full_clean(self):
        self._errors = ErrorDict()

        if not self.is_bound:  # Stop further processing.
            return

        self.cleaned_data = {}

        # If the form is permitted to be empty, and none of the form data has
        # changed from the initial data, short circuit any validation.
        if self.empty_permitted and not self.has_changed():
            return

        # Don't run _post_clean() as this will run StockItem.clean()
        self._clean_fields()
        self._clean_form()
Ejemplo n.º 8
0
 def full_clean(self):
     """
     Cleans all of self.data and populates self._errors and
     self.cleaned_data.
     """
     self._errors = ErrorDict()
     if not self.is_bound:  # Stop further processing.
         return
     self.cleaned_data = {}
     # If the form is permitted to be empty, and none of the form data has
     # changed from the initial data, short circuit any validation.
     if self.empty_permitted and not self.has_changed():
         return
     for name, field in self.fields.items():
         # value_from_datadict() gets the data from the data dictionaries.
         # Each widget type knows how to retrieve its own data, because
         # some widgets split data over several HTML fields.
         value = field.widget.value_from_datadict(self.data, self.files,
                                                  self.add_prefix(name))
         try:
             if isinstance(field, FileField):
                 initial = self.initial.get(name, field.initial)
                 value = field.clean(value, initial)
             elif isinstance(field, CharField):
                 if (value is not None and isinstance(value, basestring)
                         and len(value) > 0):
                     value = str(smart_str(value))
                 else:
                     value = field.clean(value)
             else:
                 value = field.clean(value)
             self.cleaned_data[name] = value
             if hasattr(self, 'clean_%s' % name):
                 value = getattr(self, 'clean_%s' % name)()
                 self.cleaned_data[name] = value
         except ValidationError as e:
             self._errors[name] = self.error_class(e.messages)
             if name in self.cleaned_data:
                 del self.cleaned_data[name]
     try:
         self.cleaned_data = self.clean()
     except ValidationError as e:
         self._errors[forms.Form.NON_FIELD_ERRORS] = \
             self.error_class(e.messages)
     if self._errors:
         delattr(self, 'cleaned_data')
Ejemplo n.º 9
0
    def full_clean(self):
        """验证表单并将通过验证的表单项填入映射类实例的相应字段
        """
        # self 是表单类实例
        print('【django.forms.forms.BaseForm.full_clean】表单类实例进行表单项验证')
        self._errors = ErrorDict()
        if not self.is_bound:  # Stop further processing.
            return
        self.cleaned_data = {}
        # If the form is permitted to be empty, and none of the form data has
        # changed from the initial data, short circuit any validation.
        if self.empty_permitted and not self.has_changed():
            return

        self._clean_fields()  # 验证表单信息,此方法就在下面
        self._clean_form()
        self._post_clean()  # 把合适的数据填入映射类实例的相应字段
Ejemplo n.º 10
0
    def _apply(self, data):
        '''
        Update an instance from supplied data.

        All fields marked required=True MUST be provided.
        All fields omitted will have their default used, if provided.
        '''
        self._errors = errors = ErrorDict()

        for name in self._field_names:
            if self._fields[name].readonly:
                continue

            required = self._fields[name].required
            default = self._fields[name].default

            try:
                value = data[name]
            except KeyError:
                if required:
                    if default is NOT_PROVIDED:
                        if name not in errors:
                            errors[name] = ErrorList()
                        errors[name].append(
                            ValidationError('This field is required'))
                        continue
                elif default is NOT_PROVIDED:
                    continue
                value = default
                if callable(value):
                    value = value()
            try:
                setattr(self, name, value)
            except ValidationError as e:
                if name not in errors:
                    errors[name] = ErrorList()
                errors[name].append(e)

        # Allow a final pass of cleaning
        self._clean(data, full=True)

        if self._errors:
            raise ValidationError(self._errors)

        return self._obj
Ejemplo n.º 11
0
 def full_clean(self):
     """
     Taken from Django master as of 5e06fa1469180909c51c07151692412269e51ea3
     but is mostly a copy-paste all the way back to 1.3.1
     Basically we want to keep cleaned_data around, not remove it
     if errors occured.
     """
     self._errors = ErrorDict()
     if not self.is_bound:  # Stop further processing.
         return
     self.cleaned_data = {}
     # If the form is permitted to be empty, and none of the form data has
     # changed from the initial data, short circuit any validation.
     if self.empty_permitted and not self.has_changed():
         return
     self._clean_fields()
     self._clean_form()
     self._post_clean()
Ejemplo n.º 12
0
    def full_clean(self):
        """
        Clean all of self.data and populate self._errors and self.cleaned_data.
        """
        self._errors = ErrorDict()
        if not self.is_bound:  # Stop further processing.
            return
        self.cleaned_data = {}
        # If the form is permitted to be empty, and none of the form data has
        # changed from the initial data, short circuit any validation.
        if self.empty_permitted and not self.has_changed():
            return

        # 基于字段的验证: 字段必填, 字段名匹配, 执行自定义validator
        self._clean_fields()
        # 基于表单的验证: 检查用户是否存在, 并检查密码是否一致.
        self._clean_form()
        # 验证hook.
        self._post_clean()
Ejemplo n.º 13
0
def index(request):
    if 'error' in request.GET:
        #zipcode_form = variety_trials_forms.SelectLocationByZipcodeForm(request.GET)
        zipcode_form = variety_trials_forms.SelectLocationByZipcodeForm()
        if zipcode_form._errors is None:
            zipcode_form._errors = ErrorDict()
        errors = zipcode_form._errors['zipcode'] = ErrorList(
        )  # errors for field 'zipcode'
        if request.GET['error'] == 'no_zipcode':
            errors.append(
                u"Please enter your zipcode. The retrieved data are sorted by distance from your zipcode."
            )
        elif request.GET['error'] == 'bad_zipcode':
            errors.append(u"Sorry, that zipcode didn't match any records.")
    else:
        zipcode_form = variety_trials_forms.SelectLocationByZipcodeForm()

    return render(request, 'main_ndsu.html', {
        'zipcode_form': zipcode_form,
        'home_url': HOME_URL,
    })
Ejemplo n.º 14
0
    def post(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                return super(HostUpdateCreateMixin,
                             self).post(request, *args, **kwargs)
        except ValidationError as e:
            form_class = self.get_form_class()
            form = self.get_form(form_class)
            if not getattr(form, "_errors"):
                form._errors = ErrorDict()
            error_list = form._errors.setdefault(NON_FIELD_ERRORS, ErrorList())

            if hasattr(e, "error_dict"):
                for key, errors in list(e.message_dict.items()):
                    for error in errors:
                        error_list.append(error)
            else:
                error_list.append(e.message)

            error_list.append("Please try again.")
            return self.form_invalid(form)
Ejemplo n.º 15
0
    def _clean_fields(self):
        self._errors = ErrorDict()
        num_errors = 0
        if not self.is_bound:  # Stop further processing.
            return
        self.cleaned_data = {}
        # check for 'on' checkbox value for patient relative checkbox ( which means create patient )\
        # this 'on' value from widget is replaced by the pk of the created patient
        for name, field in list(self.fields.items()):
            try:
                value = field.widget.value_from_datadict(
                    self.data, self.files, self.add_prefix(name))
                if name == "relative_patient":
                    if value == "on":
                        self.cleaned_data[name] = None
                        self.create_patient_flag = True
                    else:
                        self.cleaned_data[name] = value

                elif name == 'date_of_birth':
                    try:
                        self.cleaned_data[name] = self._set_date_of_birth(
                            value)
                    except Exception:
                        raise ValidationError(
                            "Date of Birth must be dd-mm-yyyy")

                elif name == 'patient':
                    continue  # this was causing error in post clean - we set this ourselves
                else:
                    self.cleaned_data[name] = value

            except ValidationError as e:
                num_errors += 1
                self._errors[name] = self.error_class(e.messages)
                if name in self.cleaned_data:
                    del self.cleaned_data[name]

        self.tag = self.cleaned_data["given_names"] + self.cleaned_data[
            "family_name"]
    def _clean_dependency(self, name=None):
        if name is None:
            names = self._cleaned_data.keys()
        else:
            names = [name]

        errors = ErrorDict()
        for name in names:
            if name in self._dependency:
                try:
                    field, pairs = self._dependency[name]
                    try:
                        _ = field.clean(self._cleaned_data[name])
                    except forms.ValidationError:
                        continue
                    for sub_name, sub_field in pairs:
                        _ = sub_field.clean(self._cleaned_data[sub_name])  # NOQA
                except forms.ValidationError as exc:
                    error_dict = TextErrorDict([(sub_name, exc.messages)])
                    errors[name] = [error_dict]
                    del self._cleaned_data[name]

        if errors:
            raise forms.ValidationError(errors)
 def is_valid(self):
     if "implementation_rag_rating" in self.data.keys():
         implementation_rag_rating = self.data["implementation_rag_rating"]
         required_form = self.detail_form_for_key(implementation_rag_rating)
         if required_form:
             # we need the detail form field to be required for validation,
             # but not on the client as then they can't change their minds…
             required_form.make_field_required()
             required_form_is_valid = required_form.is_valid()
             required_form.make_field_not_required()
             form_is_valid = super().is_valid()
             # now ensure that any errors on the contained forms are also on the containing form
             if self._errors is None:
                 self._errors = ErrorDict()
             if required_form.errors is not None:
                 for field, error in required_form.errors.items():
                     self._errors[f"{field}"] = error
             return all(
                 (
                     form_is_valid,
                     required_form_is_valid,
                 )
             )
     return super().is_valid()
Ejemplo n.º 18
0
    def full_clean(self):
        """
        Cleans all of self.data and populates self._errors and
        self.cleaned_data.
        """
        self._errors = ErrorDict()
        # Stop further processing.
        if not self.is_bound:
            return
        self.cleaned_data = {}
        # If the form is permitted to be empty, and none of the form data has
        # changed from the initial data, short circuit any validation.
        if self.empty_permitted and not self.has_changed():
            return
        self._clean_fields()
        # UPDATE: 如果输入数据通过不了field本身的校验,直接返回错误信息,
        # 不进行接下来的验证
        if not self.is_valid():
            return

        self._clean_form()
        self._post_clean()
        if self._errors:
            del self.cleaned_data
Ejemplo n.º 19
0
def edit_password(request):
    if request.user.is_authenticated and request.user.doctor.role == "Doctor":
        if request.POST:
            oldpass = request.POST["passwordold"]
            user = request.user.username
            user = authenticate(username=user, password=oldpass)
            if user is not None:
                try:
                    passwordnew1 = request.POST["passwordnew1"]
                    password_validation.validate_password(passwordnew1)
                except Exception as e:
                    errAsDict = {
                        'password': ErrorDict({'': '\n'.join(e.messages)})
                    }
                    return render(request, 'doctor/edit_password.html',
                                  {'errors': ErrorDict(errAsDict)})
                passwordnew2 = request.POST["passwordnew2"]
                if passwordnew1 != passwordnew2:
                    return render(
                        request, 'doctor/edit_password.html', {
                            'errors':
                            ErrorDict({
                                "Password":
                                ErrorDict({'': "Passwords do not match"})
                            })
                        })
                user.set_password(passwordnew1)
                user.save()
                login(request, user)
                return redirect('/doctor/dashboard/')
            else:
                return render(
                    request, 'doctor/edit_password.html', {
                        'errors':
                        ErrorDict({
                            "Password":
                            ErrorDict({'': "Old password is incorrect"})
                        })
                    })
        return render(request, 'doctor/edit_password.html')
    return redirect('/doctor/login/')
Ejemplo n.º 20
0
    def errors(self):
        _errors = ErrorDict()
        for form in self._subforms:
            _errors.update({self._get_error_key(form.prefix, name): error for name, error in form.errors.items()})

        return _errors
Ejemplo n.º 21
0
class NgModelFormMixin(NgFormBaseMixin):
    """
    Add this NgModelFormMixin to every class derived from ``forms.Form``, if that custom ``Form``
    shall be managed through an Angular controller.
    It adds attributes ``ng-model``, and optionally ``ng-change``, ``ng-class`` and ``ng-style``
    to each of your input fields.
    If form validation fails, the ErrorDict is rewritten in a way, so that the Angular controller
    can access the error strings using the same key values as for its models.
    """
    add_djng_error = False

    def __init__(self, data=None, *args, **kwargs):
        self.scope_prefix = kwargs.pop('scope_prefix', getattr(self, 'scope_prefix', None))
        self.ng_directives = {}
        for key in list(kwargs.keys()):
            if key.startswith('ng_'):
                fmtstr = kwargs.pop(key)
                self.ng_directives[key.replace('_', '-')] = fmtstr
        if hasattr(self, 'Meta') and hasattr(self.Meta, 'ng_models'):
            if not isinstance(getattr(self.Meta, 'ng_models'), list):
                raise TypeError('Meta.ng_model is not of type list')
        elif 'ng-model' not in self.ng_directives:
            self.ng_directives['ng-model'] = '%(model)s'
        self.prefix = kwargs.get('prefix')
        if self.prefix and data:
            if data.get(self.prefix):
                data = {self.add_prefix(name): value for (name, value) in data.get(self.prefix).items()}
            else:
                data = {name : value for (name, value) in data.items() if name.startswith(self.prefix + '.')}	
        super(NgModelFormMixin, self).__init__(data, *args, **kwargs)
        if self.scope_prefix == self.form_name:
            raise ValueError("The form's name may not be identical with its scope_prefix")

    def _post_clean(self):
        """
        Rewrite the error dictionary, so that its keys correspond to the model fields.
        """
        super(NgModelFormMixin, self)._post_clean()
        if self._errors and self.prefix:
            self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._errors.items())

    def get_initial_data(self):
        """
        Return a dictionary specifying the defaults for this form. This dictionary can be used to
        inject the initial values for an Angular controller using the directive:
        ``ng-init={{ thisform.get_initial_data|js|safe }}``.
        """
        data = {}
        ng_models = hasattr(self, 'Meta') and getattr(self.Meta, 'ng_models', []) or []
        for name, field in self.fields.items():
            if 'ng-model' in self.ng_directives or name in ng_models:
                data[name] = self.initial.get(name) if self.initial else field.initial
        return data

    def get_field_errors(self, field):
        errors = super(NgModelFormMixin, self).get_field_errors(field)
        if field.is_hidden:
            return errors
        identifier = format_html('{0}.{1}', self.form_name, field.html_name)
        errors.append(SafeTuple((identifier, self.field_error_css_classes, '$pristine', '$message', 'invalid', '$message')))
        return errors

    def non_field_errors(self):
        errors = super(NgModelFormMixin, self).non_field_errors()
        errors.append(SafeTuple((self.form_name, self.form_error_css_classes, '$pristine', '$message', 'invalid', '$message')))
        return errors

    def get_widget_attrs(self, bound_field):
        attrs = super(NgModelFormMixin, self).get_widget_attrs(bound_field)
        identifier = self.add_prefix(bound_field.name)
        ng = {
            'name': bound_field.name,
            'identifier': identifier,
            'model': ('%s[\'%s\']' % (self.scope_prefix, identifier)) if self.scope_prefix else identifier
        }
        if hasattr(self, 'Meta') and bound_field.name in getattr(self.Meta, 'ng_models', []):
            attrs['ng-model'] = ng['model']
        for key, fmtstr in self.ng_directives.items():
            attrs[key] = fmtstr % ng
        return attrs
Ejemplo n.º 22
0
 def add_form_error(self, message):
     if not self._errors:
         self._errors = ErrorDict()
     if not NON_FIELD_ERRORS in self._errors:
         self._errors[NON_FIELD_ERRORS] = self.error_class()
     self._errors[NON_FIELD_ERRORS].append(message)
Ejemplo n.º 23
0
 def full_clean(self):
     super(AddressForm, self).full_clean()
     if self.is_bound and self['use_primary_address'].value():
         # reset errors, since then the form is always regarded as valid
         self._errors = ErrorDict()
Ejemplo n.º 24
0
 def full_clean(self):
     if self.data.get(self.prefix + '-remove') != 'on':
         super().full_clean()
     else:
         self._errors = ErrorDict()
         self.cleaned_data = {'remove': True}
Ejemplo n.º 25
0
                        current_data['grade_min'] = Tag.getProgramTag(
                            'teacherreg_default_min_grade', prog)
                    if 'grade_max' in hidden_fields:
                        current_data['grade_max'] = Tag.getProgramTag(
                            'teacherreg_default_max_grade', prog)
                    if 'class_size_max' in hidden_fields:
                        current_data['class_size_max'] = Tag.getProgramTag(
                            'teacherreg_default_class_size_max', prog)

                if not populateonly:
                    context['class'] = newclass

                if action == 'edit':
                    reg_form = TeacherClassRegForm(self.crmi, current_data)
                    # TODO: remove private API use
                    if populateonly: reg_form._errors = ErrorDict()
                elif action == 'editopenclass':
                    reg_form = TeacherOpenClassRegForm(self.crmi, current_data)
                    # TODO: remove private API use
                    if populateonly: reg_form._errors = ErrorDict()

                #   Todo...
                ds = newclass.default_section()
                class_requests = ResourceRequest.objects.filter(target=ds)
                #   Program the multiple-checkbox forms if static requests are used.
                resource_formset = ResourceRequestFormSet(
                    resource_type=resource_types, prefix='request')
                initial_requests = {}
                for x in class_requests:
                    if x.res_type.name not in initial_requests:
                        initial_requests[x.res_type.name] = []
Ejemplo n.º 26
0
    def test_validation_error(self):
        ###################
        # ValidationError #
        ###################

        # Can take a string.
        self.assertHTMLEqual(
            str(ErrorList(ValidationError("There was an error.").messages)),
            '<ul class="errorlist"><li>There was an error.</li></ul>')

        # Can take a unicode string.
        self.assertHTMLEqual(
            six.text_type(ErrorList(ValidationError("Not \u03C0.").messages)),
            '<ul class="errorlist"><li>Not π.</li></ul>')

        # Can take a lazy string.
        self.assertHTMLEqual(
            str(ErrorList(ValidationError(ugettext_lazy("Error.")).messages)),
            '<ul class="errorlist"><li>Error.</li></ul>')

        # Can take a list.
        self.assertHTMLEqual(
            str(
                ErrorList(
                    ValidationError(["Error one.", "Error two."]).messages)),
            '<ul class="errorlist"><li>Error one.</li><li>Error two.</li></ul>'
        )

        # Can take a mixture in a list.
        self.assertHTMLEqual(
            str(
                ErrorList(
                    ValidationError([
                        "First error.", "Not \u03C0.",
                        ugettext_lazy("Error.")
                    ]).messages)),
            '<ul class="errorlist"><li>First error.</li><li>Not π.</li><li>Error.</li></ul>'
        )

        @python_2_unicode_compatible
        class VeryBadError:
            def __str__(self):
                return "A very bad error."

        # Can take a non-string.
        self.assertHTMLEqual(
            str(ErrorList(ValidationError(VeryBadError()).messages)),
            '<ul class="errorlist"><li>A very bad error.</li></ul>')

        # Escapes non-safe input but not input marked safe.
        example = 'Example of link: <a href="http://www.example.com/">example</a>'
        self.assertHTMLEqual(
            str(ErrorList([example])),
            '<ul class="errorlist"><li>Example of link: &lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>'
        )
        self.assertHTMLEqual(
            str(ErrorList([mark_safe(example)])),
            '<ul class="errorlist"><li>Example of link: <a href="http://www.example.com/">example</a></li></ul>'
        )
        self.assertHTMLEqual(
            str(ErrorDict({'name': example})),
            '<ul class="errorlist"><li>nameExample of link: &lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>'
        )
        self.assertHTMLEqual(
            str(ErrorDict({'name': mark_safe(example)})),
            '<ul class="errorlist"><li>nameExample of link: <a href="http://www.example.com/">example</a></li></ul>'
        )
Ejemplo n.º 27
0
 def full_clean(self):
     super(AddressForm, self).full_clean()
     if not self.is_primary:
         if self.is_bound and self['use_primary_address'].value():
             self._errors = ErrorDict()
Ejemplo n.º 28
0
 def full_clean(self):
     if len(self.data) == 0:
         # form wasn't submitted
         self._errors = ErrorDict()
         return
     super().full_clean()
Ejemplo n.º 29
0
 def test_error_dict_html_safe(self):
     e = ErrorDict()
     e['username'] = '******'
     self.assertTrue(hasattr(ErrorDict, '__html__'))
     self.assertEqual(force_text(e), e.__html__())
Ejemplo n.º 30
0
    def test_validation_error(self):
        ###################
        # ValidationError #
        ###################

        # Can take a string.
        self.assertHTMLEqual(
            str(ErrorList(ValidationError("There was an error.").messages)),
            '<ul class="errorlist"><li>There was an error.</li></ul>')
        # Can take a unicode string.
        self.assertHTMLEqual(
            str(ErrorList(ValidationError("Not \u03C0.").messages)),
            '<ul class="errorlist"><li>Not π.</li></ul>')
        # Can take a lazy string.
        self.assertHTMLEqual(
            str(ErrorList(ValidationError(gettext_lazy("Error.")).messages)),
            '<ul class="errorlist"><li>Error.</li></ul>')
        # Can take a list.
        self.assertHTMLEqual(
            str(
                ErrorList(
                    ValidationError(["Error one.", "Error two."]).messages)),
            '<ul class="errorlist"><li>Error one.</li><li>Error two.</li></ul>'
        )
        # Can take a dict.
        self.assertHTMLEqual(
            str(
                ErrorList(
                    sorted(
                        ValidationError({
                            'error_1': "1. Error one.",
                            'error_2': "2. Error two."
                        }).messages))),
            '<ul class="errorlist"><li>1. Error one.</li><li>2. Error two.</li></ul>'
        )
        # Can take a mixture in a list.
        self.assertHTMLEqual(
            str(
                ErrorList(
                    sorted(
                        ValidationError([
                            "1. First error.",
                            "2. Not \u03C0.",
                            gettext_lazy("3. Error."),
                            {
                                'error_1': "4. First dict error.",
                                'error_2': "5. Second dict error.",
                            },
                        ]).messages))), '<ul class="errorlist">'
            '<li>1. First error.</li>'
            '<li>2. Not π.</li>'
            '<li>3. Error.</li>'
            '<li>4. First dict error.</li>'
            '<li>5. Second dict error.</li>'
            '</ul>')

        class VeryBadError:
            def __str__(self):
                return "A very bad error."

        # Can take a non-string.
        self.assertHTMLEqual(
            str(ErrorList(ValidationError(VeryBadError()).messages)),
            '<ul class="errorlist"><li>A very bad error.</li></ul>')

        # Escapes non-safe input but not input marked safe.
        example = 'Example of link: <a href="http://www.example.com/">example</a>'
        self.assertHTMLEqual(
            str(ErrorList([example])),
            '<ul class="errorlist"><li>Example of link: '
            '&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>'
        )
        self.assertHTMLEqual(
            str(ErrorList([mark_safe(example)])),
            '<ul class="errorlist"><li>Example of link: '
            '<a href="http://www.example.com/">example</a></li></ul>')
        self.assertHTMLEqual(
            str(ErrorDict({'name': example})),
            '<ul class="errorlist"><li>nameExample of link: '
            '&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>'
        )
        self.assertHTMLEqual(
            str(ErrorDict({'name': mark_safe(example)})),
            '<ul class="errorlist"><li>nameExample of link: '
            '<a href="http://www.example.com/">example</a></li></ul>')
Ejemplo n.º 31
0
 def errors(self):
     errors = ErrorDict(super(forms.Form, self).errors)
     if not self.is_sign_up():
         errors.pop('password_confirm', None)
         errors.pop('name', None)
     return errors
Ejemplo n.º 32
0
class APIForm(forms.Form):
    def full_clean(self):
        """
        Clean all of self.data and populate self._errors and self.cleaned_data.
        """
        self._errors = ErrorDict()
        if not self.is_bound:  # Stop further processing.
            return
        self.cleaned_data = {}
        # If the form is permitted to be empty, and none of the form data has
        # changed from the initial data, short circuit any validation.
        if self.empty_permitted and not self.has_changed():
            return

        self._clean_fields()
        if len(self._errors) > 0:
            return

        self._clean_form()
        if len(self._errors) > 0:
            return

        self._post_clean()

    def _clean_fields(self):
        for name, field in self.fields.items():
            self._clean_field(name, field)

    def _clean_field(self, name, field):
        # value_from_datadict() gets the data from the data dictionaries.
        # Each widget type knows how to retrieve its own data, because some
        # widgets split data over several HTML fields.
        if field.disabled:
            value = self.get_initial_for_field(field, name)
        else:
            value = field.widget.value_from_datadict(self.data, self.files,
                                                     self.add_prefix(name))
        if value is None and field.required:
            value = self.get_initial_for_field(field, name)

        try:
            if isinstance(field, FileField):
                initial = self.get_initial_for_field(field, name)
                value = field.clean(value, initial)
            else:
                value = field.clean(value)

            self.cleaned_data[name] = value
            if hasattr(self, 'clean_%s' % name):
                value = getattr(self, 'clean_%s' % name)()
                self.cleaned_data[name] = value
        except ValidationError as e:
            self.add_error(name, e)

    def get_initial_for_field(self, field, field_name):
        """
        Return initial data for field on form. Use initial data from the form
        or the field, in that order. Evaluate callable values.
        """
        value = self.initial.get(field_name, field.initial)
        if value is None:
            vale = field.initial
        if callable(value):
            value = value()
        return value

    def add_prefix(self, field_name):
        field = self.fields[field_name]
        if field.label is not None:
            return field.label
        return field_name

    def _post_clean(self):
        if hasattr(self, 'name_map'):
            self.cleaned_data = {
                self.name_map[k] if k in self.name_map else k: v
                for k, v in self.cleaned_data.items()
            }

    def get_errors(self):
        errors = {}
        for name, value in self._errors.items():
            if name != NON_FIELD_ERRORS:
                errors[self.add_prefix(name)] = value
            else:
                errors[NON_FIELD_ERRORS] = value
        return errors
Ejemplo n.º 33
0
 def __init__(self, initial, data=None, files=None):
     self.data = data or {}
     self.files = files or {}
     self.errors = ErrorDict()
     self.initial = initial
Ejemplo n.º 34
0
def order_create(request):
    if request.method == "POST":
        if request.user.is_authenticated:
            form = CabinetOrderForm(request.POST)
        else:
            form = OrderForm(request.POST, initial={})

        novalidate = int(request.POST.get('novalidate', 0))

        if form.is_valid():
            order = form.save(commit=False)
            if request.user.is_authenticated:
                order.user = request.user
            else:
                order.user = User.objects.filter(
                    email=form.cleaned_data.get('email')).first()

                if not order.user_id:

                    plain_password = randomStringDigits(8)

                    order.user = User.register(form.cleaned_data.get('name'),
                                               form.cleaned_data.get('email'),
                                               form.cleaned_data.get('phone'),
                                               plain_password)
                    if not order.user_id:
                        messages.add_message(
                            request, messages.ERROR,
                            'Регистрация не удалась, хрень какая-то')
                        return HttpResponse(
                            'Регистрация не удалась, хрень какая-то')
                    else:
                        messages.add_message(
                            request, messages.SUCCESS,
                            'Ваша заявка зарегистрирована. На вашу электронную почту выслан доступ в личный кабинет.'
                        )
                        d = {
                            'user': order.user,
                            'plain_password': plain_password
                        }
                        template_t = get_template('email/user-registered.txt')
                        message = template_t.render(d)
                        try:
                            send_mail('Регистрация на сайте', message,
                                      settings.DEFAULT_FROM_EMAIL,
                                      [order.user.email])
                        except BadHeaderError:
                            return HttpResponse('Invalid header found.')
                else:
                    messages.add_message(request, messages.SUCCESS,
                                         'Ваша заявка зарегистрирована')

            order.save()

            d = {'user': order.user, 'order': order}
            template_t = get_template('email/user-order-created.txt')
            template_a = get_template('email/adm-order-created.txt')
            message_a = template_a.render(d)
            message_t = template_t.render(d)
            try:
                send_mail('Заказ', message_a, settings.DEFAULT_FROM_EMAIL,
                          [settings.NOTIFY_EMAIL])
                send_mail('Оформление заказа на сайте', message_t,
                          settings.DEFAULT_FROM_EMAIL, [order.user.email])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')

            messages.add_message(
                request, messages.SUCCESS, 'Ваш ' + str(order) +
                ' оформлен и поступил на обработку к нашим менеджерам. Обработка выполняется в '
                'течении нескольких рабочих часов, по результатам обработки вы получите счет на '
                'оплату услуг. В случае возникновения вопросов менеджер свяжется с вами.'
            )

            return redirect(reverse('orders.created'))
        else:
            form._errors = ErrorDict()
            form.full_clean = form._full_clean

    else:
        if request.user.is_authenticated:
            form = CabinetOrderForm()
        else:
            form = OrderForm()

    return render(request, 'website/cabinet/orders-create.html',
                  {'form': form})
Ejemplo n.º 35
0
 def full_clean(self):
     if not self.instance.id:
         self.cleaned_data = {}
         self._errors = ErrorDict()
         return
     return super().full_clean()
Ejemplo n.º 36
0
    def post(self, request, *args, **kwargs):
        print(request.POST)

        response_dict = {}

        if request.POST.get('form_key') == 'edit_profile':
            form_a = self.user_form(pk=request.user.pk, data=request.POST)
            form_b = self.profile_form(user=request.user, data=request.POST)

            errors = ErrorDict()
            if form_a.errors:
                errors.update(form_a.errors)

            if form_b.errors:
                errors.update(form_b.errors)

            if not (form_a.is_valid() and form_b.is_valid()):
                response_dict.update({
                    'status': 0,
                    'message': errors.as_ul()
                })

            elif authenticate(username=request.user.username, password=request.POST.get('password')):
                u1 = form_a.save()
                u2 = form_b.save()

                response_dict.update({
                    'status': 1,
                    'message': 'User was successfully updated.',
                    'instance': {
                        'username': u1.username,
                        'email': u1.email,
                        'about_me': u2.about_me,
                    }
                })
            else:
                response_dict.update({
                    'status': 0,
                    'message': 'Password is incorrect.'
                })

            return HttpResponse(json.dumps(response_dict, cls=DjangoJSONEncoder))

        elif request.POST.get('form_key') == 'change_pw':
            form = self.password_form(pk=request.user.pk, data=request.POST)

            if not form.is_valid():
                response_dict.update({
                    'status': 0,
                    'message': form.errors.as_ul()
                })
            elif authenticate(username=request.user.username, password=request.POST.get('old_password')):
                form.save()
                response_dict.update({
                    'status': 1,
                    'message': 'Password was successfully updated.'
                })
            else:
                response_dict.update({
                    'status': 0,
                    'message': 'Old password is incorrect.'
                })

            return HttpResponse(json.dumps(response_dict, cls=DjangoJSONEncoder))
        return super(ProfileView, self).get(request, *args, **kwargs)
Ejemplo n.º 37
0
 def test_error_dict_html_safe(self):
     e = ErrorDict()
     e['username'] = '******'
     self.assertTrue(hasattr(ErrorDict, '__html__'))
     self.assertEqual(force_text(e), e.__html__())
Ejemplo n.º 38
0
 def full_clean(self):
     self._errors = ErrorDict()
     if hasattr(self, 'cleaned_data'):
         del self.cleaned_data