How to use the deform.ValidationFailure function in deform

To help you get started, we’ve selected a few deform examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github websauna / websauna / websauna / system / user / views.py View on Github external
settings = request.registry.settings

    schema = request.registry.getUtility(IRegisterSchema)
    schema = schema().bind(request=request)

    form_class = request.registry.getUtility(IRegisterForm)
    form = form_class(schema)

    social_logins = aslist(settings.get("websauna.social_logins", ""))

    if request.method == "POST":
        # If the request is a POST:
        controls = request.POST.items()
        try:
            captured = form.validate(controls)
        except deform.ValidationFailure as e:
            return {'form': e.render(), 'errors': e.error.children, 'social_logins': social_logins}

        # With the form validated, we know email and username are unique.
        del captured['csrf_token']

        registration_service = get_registration_service(request)
        return registration_service.sign_up(user_data=captured)

    return {'form': form.render(), 'social_logins': social_logins}
github websauna / websauna / websauna / system / crud / views.py View on Github external
form = self.get_form()

        crud = self.get_crud()

        title = self.get_title()

        if "save" in self.request.POST:

            controls = self.request.POST.items()

            try:
                appstruct = form.validate(controls)
                self.save_changes(form, appstruct, obj)
                return self.do_success()

            except deform.ValidationFailure as e:
                # Whoops, bad things happened, render form with validation errors
                rendered_form = e.render()

        elif "cancel" in self.request.POST:
            # User pressed cancel
            return self.do_cancel()
        else:
            # Render initial form view with populated values
            appstruct = self.get_appstruct(form, obj)
            rendered_form = form.render(appstruct)

        self.pull_in_widget_resources(form)

        return dict(form=rendered_form, context=self.context, obj=obj, title=title, crud=crud, base_template=base_template, resource_buttons=self.get_resource_buttons(), current_view_name="Edit")
github VoteIT / voteit.core / voteit / core / views / export_import.py View on Github external
raise HTTPForbidden("You're not allowed to access this view")
        redirect_url = resource_url(self.context, self.request)
        export_import = self.request.registry.queryAdapter(self.api.root, IExportImport)
        if not export_import:
            msg = _(u"ExportImport component not included in VoteIT. You need to register it to use this.")
            self.api.flash_messages.add(msg, type = 'error')
            return HTTPFound(location=redirect_url)
        schema = createSchema('ImportSchema').bind(context = self.context, request = self.request)
        form = deform.Form(schema, buttons=(button_save, button_cancel))
        self.api.register_form_resources(form)

        if 'save' in self.request.POST:
            controls = self.request.params.items()
            try:
                appstruct = form.validate(controls)
            except deform.ValidationFailure, e:
                self.response['form'] = e.render()
                return self.response

            name = appstruct['name']
            filedata = appstruct['upload']
            export_import.import_data(self.context, name, filedata['fp'])
            filedata.clear()
            self.api.flash_messages.add(_(u"Created new objects from import"))
            return HTTPFound(location=redirect_url)

        if 'cancel' in self.request.POST:
            self.api.flash_messages.add(_(u"Canceled"))
            return HTTPFound(location=redirect_url)

        #No action
        msg = _(u"Import file to current context")
github nandoflorestan / bag / bag / web / pyramid / deform_view.py View on Github external
def _post(self, form, controls=None):
        """You may override this method in subclasses to do something special.

        ...when the request method is POST.
        """
        controls = peppercorn.parse(controls or self.request.POST.items())
        controls = self._preprocess_controls(controls)
        try:
            appstruct = form.validate_pstruct(controls)
        except d.ValidationFailure as e:
            self.status = 'invalid'
            return self._invalid(e, controls)
        else:
            self.status = 'valid'
            appstruct.pop('csrf_token', None)  # Discard the CSRF token
            return self._valid(form=form, controls=appstruct)
github hypothesis / h / h / form.py View on Github external
should be returned if this is not an XHR request.

        If on_success() returns ``None`` then ``handle_form_submission()``
        will return ``HTTPFound(location=request.url)`` by default.
    :type on_success: callable

    :param on_failure:
        A callback function that will be called if form validation fails in
        order to get the view callable result that should be returned if this is
        not an XHR request.
    :type on_failure: callable

    """
    try:
        appstruct = form.validate(request.POST.items())
    except deform.ValidationFailure:
        result = on_failure()
        request.response.status_int = 400
    else:
        result = on_success(appstruct)

        if result is None:
            result = httpexceptions.HTTPFound(location=request.url)

        if not request.is_xhr:
            request.session.flash(_("Success. We've saved your changes."), "success")

    return to_xhr_response(request, result, form)
github hypothesis / h / h / views / account_signup.py View on Github external
def post(self):
        """
        Handle submission of the new user registration form.

        Validates the form data, creates a new activation for the user, sends
        the activation mail, and then redirects the user to the index.
        """
        self._redirect_if_logged_in()

        try:
            appstruct = self.form.validate(self.request.POST.items())
        except deform.ValidationFailure:
            return {"form": self.form.render()}

        signup_service = self.request.find_service(name="user_signup")

        template_context = {"heading": _("Account registration successful")}
        try:
            signup_service.signup(
                username=appstruct["username"],
                email=appstruct["email"],
                password=appstruct["password"],
                privacy_accepted=datetime.datetime.utcnow(),
            )
        except ConflictError as e:
            template_context["heading"] = _("Account already registered")
            template_context["message"] = _(
                "{failure_reason}".format(failure_reason=e.args[0])
github hypothesis / h / h / views / accounts.py View on Github external
@json_view(context=deform.ValidationFailure)
def error_validation(error, request):
    request.response.status_code = 400
    return ajax_payload(request, {"status": "failure", "errors": error.error.asdict()})
github Akagi201 / learning-python / pyramid / MyShop / myshop / views.py View on Github external
@view_config(route_name='login', renderer='templates/login.pt')
def login_view(request):
    deform_static.need()

    search_path = ('myShop/templates/deform/',)
    renderer = deform.ZPTRendererFactory(search_path)
    schema = LoginFormSchema(validator=password_validator)
    form = deform.Form(schema, buttons=('submit',), renderer=renderer)

    if 'submit' in request.POST:
        try:
            appstruct = form.validate(request.POST.items())
        except deform.ValidationFailure, e:
            return {
                'title': 'login',
                'form': e.render()
            }

        user = appstruct['login']

        headers = remember(request, user.id)
        return HTTPFound(location='/', headers=headers)

    return {
        'title': 'login',
        'form': form.render()
    }
github domenkozar / almir / almir / views.py View on Github external
return

        schema = self.schema()

        form = Form(schema.bind(**self.context),
                    buttons=[],
                    bootstrap_form_style='form-vertical')

        if self.request.query_string:
            controls = self.request.GET.items()

            try:
                self.context['appstruct'] = form.validate(controls)
                self.request.session[self.schema.__name__] = self.context['appstruct']
                self.request.session.save()
            except ValidationFailure, e:
                return e

        appstruct = self.request.session.get(self.schema.__name__, None)
        if appstruct:
            return form.render(appstruct)
        else:
            return form.render()
github hypothesis / h / h / views / accounts.py View on Github external
def post(self):
        """Log the user in and redirect them."""
        self._redirect_if_logged_in()

        try:
            appstruct = self.form.validate(self.request.POST.items())
        except deform.ValidationFailure:
            return {"form": self.form.render()}

        user = appstruct["user"]
        headers = self._login(user)
        return httpexceptions.HTTPFound(
            location=self._login_redirect(), headers=headers
        )