コード例 #1
0
ファイル: views.py プロジェクト: WasatchPhotonics/StickerCode
    def qr_label(self):
        """ Process form parameters, create a qr code or return an empty
        form.
        """
        form = Form(StickerSchema(), buttons=("submit",))

        if "submit" in self.request.POST:
            #log.info("submit: %s", self.request.POST)
            controls = self.request.POST.items()
            try:
                appstruct = form.validate(controls)
                rendered_form = form.render(appstruct)

                self.write_optional_uploads(appstruct)
                self.check_background_size(appstruct)
                self.build_qr_label(appstruct) 

                return {"form":rendered_form, "appstruct":appstruct}

            except ValidationFailure as exc: 
                #log.exception(exc)
                log.info("Validation failure")
                return {'form':exc.render()} 

        return {"form":form.render()}
コード例 #2
0
ファイル: views.py プロジェクト: rijkstofberg/pyramid.payment
    def order_view(self):
        schema = OrderSchema()
        form = Form(schema,
                    css_class='vertical_form',
                    buttons=('Confirm order',))

        if 'Confirm_order' in self.request.POST:
            order = Order(
                description = self.request.POST['description'],
                value = self.request.POST['value']
            )

            controls = self.request.POST.items()
            try:
                appstruct = form.validate(controls)
                DBSession.add(order)
                DBSession.flush()
                url = self.request.route_url('confirm')
                url = url + '?order_id=%s' % order.id
                return HTTPFound(location = url)
            except ValidationFailure:
                appstruct = order.as_dict()
                return {'form': form.render(appstruct)}
        elif 'product_id' in self.request.params:
            product = Product.by_id(int(self.request.params.get('product_id')))
            order = Order(product.description, product.price)
            schema.get('display_value').missing = product.price
            appstruct = order.as_dict()
            return {'form': form.render(appstruct),
                    'order': order}
        return {}
コード例 #3
0
    def calibration_report(self):
        """ Process form paramters, create a pdf calibration report form
        and generate a thumbnail view.
        """
        form = Form(ReportSchema(), buttons=("submit",))

        if "submit" in self.request.POST:
            #log.info("submit: %s", self.request.POST)
            controls = self.request.POST.items()
            try:
                appstruct = form.validate(controls)
                rendered_form = form.render(appstruct)

                report = self.populate_data(appstruct)
                self.makedir_write_files(appstruct)
                pdf = WasatchSinglePage(filename=report.filename,
                                        report=report)
                pdf.write_thumbnail()

                return {"form":rendered_form, "appstruct":appstruct}

            except ValidationFailure as exc: 
                #log.exception(exc)
                log.info("Validation failure")
                return {'form':exc.render()} 

        return {"form":form.render()}
コード例 #4
0
ファイル: user.py プロジェクト: arthens/triage
def login(request):

    schema = UserLoginSchema(validator=user_login_validator)
    form = Form(schema, buttons=('submit',))

    userid = authenticated_userid(request)
    if userid:
        return HTTPFound(location='/')

    if 'submit' in request.POST:
        controls = request.POST.items()

        try:
            values = form.validate(controls)

            try:
                user = User.objects.get(email=values['email'])
                user.tzoffset = values['tzoffset']
                user.save()
            except DoesNotExist:
                return HTTPNotFound()

            headers = remember(request, str(user.id), max_age=10000000000)
            return HTTPFound(location='/', headers=headers)
        except ValidationFailure:
            form_render = form.render()
    else:
        form_render = form.render()

    params = {
        'form': Markup(form_render)
    }

    return render_to_response('user/login.html', params)
コード例 #5
0
ファイル: user.py プロジェクト: mikoop79/triage
def login(request):

    schema = UserLoginSchema(validator=user_login_validator)
    form = Form(schema, buttons=("submit",))

    userid = authenticated_userid(request)
    if userid:
        return HTTPFound(location="/")

    if "submit" in request.POST:
        controls = request.POST.items()

        try:
            values = form.validate(controls)

            try:
                user = User.objects.get(email=values["email"])
            except DoesNotExist:
                return HTTPNotFound()

            headers = remember(request, str(user.id))
            return HTTPFound(location="/", headers=headers)
        except ValidationFailure:
            form_render = form.render()
    else:
        form_render = form.render()

    params = {"form": Markup(form_render)}

    return render_to_response("user/login.html", params)
コード例 #6
0
ファイル: users.py プロジェクト: rhaamo/codular
    def update_user(self):
        template_vars = {'menu_active': 'update_user'}
        form = Form(Registration().bind(request=self.request), buttons=('submit',),
                action=self.request.route_url('update_user'))
        if 'submit' in self.request.POST: # detect that the submit button was clicked

            controls = self.request.POST.items() # get the form controls

            try:
                form_data = form.validate(controls)  # call validate
            except ValidationFailure as e: # catch the exception
                template_vars['form'] = form.render() # re-render the form with an exception
                return template_vars

            # if user is logged, we update his profile. Else we create a new user.
            userid = authenticated_userid(self.request)
            if userid:
                user =  User.by_id(userid)
                # WARNING: only update authorized values

            else:
                del(form_data['csrf'])
                user = User(**form_data)
                DBSession.add(user)

            url = self.request.route_url('home')
            return HTTPFound(location=url)
        template_vars['form'] = form.render()
        return template_vars
コード例 #7
0
ファイル: views.py プロジェクト: WasatchPhotonics/PDFExploder
    def generate_thumbnails(self):
        """ Display the form on get, on submission, save the uploaded
        pdf to the "serial" directory, and return the form populated 
        along with the generated thumbnails.
        """
        form = Form(PDFUploadSchema(), buttons=("submit",))

        if "submit" in self.request.POST:
            log.info("submit: %s", self.request.POST)

            controls = self.request.POST.items()
            try:
                appstruct = form.validate(controls)
                rendered_form = form.render(appstruct)

                self.write_upload_files(appstruct)
                self.write_thumbnails(appstruct)

                return {"form":rendered_form, "appstruct":appstruct}

            except ValidationFailure as exc: 
                log.info("Validation failure")
                return {'form':exc.render()} 

        return {"form":form.render()}
コード例 #8
0
ファイル: issues.py プロジェクト: jayd3e-archive/RepRap
 def view(self):
     title = "View Issue"
     issue_id = self.matchdict['id']
     
     db = self.request.db
     issue = db.query(IssuesModel).filter_by(id=issue_id).first()
     
     add_issue_comment_schema = AddIssueCommentSchema()
     add_issue_comment_button = Button(name="comment_submit", title="Add Comment")
     add_issue_comment_form = Form(add_issue_comment_schema, buttons=[add_issue_comment_button])
     add_issue_comment_form['body'].title = False
     
     add_tag_schema = AddTagSchema()
     add_tag_form = Form(add_tag_schema, css_class='add_tag_form')
     add_tag_form['tags'].title = False
     
     if 'comment_submit' in self.request.POST:
         controls = self.request.POST.items()
         try:
             captured = add_issue_comment_form.validate(controls)
         except ValidationFailure as e:
             return {'add_issue_comment_form':e.render(),
                     'add_tag_form':add_tag_form.render(),
                     'here':self.here,
                     'issue':issue,
                     'title':title}
         db = self.request.db
         
         issue_comment = IssueCommentsModel(body=captured['body'],
                                            created=datetime.now(),
                                            change_time=datetime.now())
         issue.comments.append(issue_comment)
         
         db.flush()
         return HTTPFound(location="/issues/view/" + str(issue.id))
     elif 'tags' in self.request.POST:
         controls = self.request.POST.items()
         try:
             captured = add_tag_form.validate(controls)
         except ValidationFailure as e:
             return {'add_tag_form':e.render(),
                     'add_issue_comment_form':add_issue_comment_form.render(),
                     'here':self.here,
                     'issue':issue,
                     'title':title}
         db = self.request.db
         
         tags = self.separateTags(captured['tags'])
         for tag in tags:
             issue.tags.append(TagsModel(name=tag))
         
         db.flush()
         return HTTPFound(location="/issues/view/" + str(issue.id))
     
     return {'title':title,
             'here':self.here,
             'issue':issue,
             'add_tag_form':add_tag_form.render(),
             'add_issue_comment_form':add_issue_comment_form.render()}
コード例 #9
0
def demo_form(request):
    form = Form(DemoSchema(), buttons=('Save',))
    if request.method == 'POST':
        controls = request.params.items()
        try:
            params = form.validate(controls)
            logger.debug("OK")
            logger.debug("result = {}".format(params))
            return dict(form=form.render(),
                        result=params)
        except ValidationFailure as e:
            return dict(form=e.render(),
                        result=None)
    return dict(form=form.render(),
                result=None)
コード例 #10
0
ファイル: ap_invoice_skpd.py プロジェクト: aagusti/zosipkd
def view_edit_unposting(request):
    row = query_id(request).first()
    
    if not row:
        return id_not_found(request)
    if not row.posted:
        request.session.flash('Data tidak dapat di Unposting, karena belum diposting.', 'error')
        return route_list(request)
    if row.disabled:
        request.session.flash('Data jurnal Tagihan sudah diposting.', 'error')
        return route_list(request)
        
    form = Form(colander.Schema(), buttons=('unposting','cancel'))
    
    if request.POST:
        if 'unposting' in request.POST: 
        
            #Update status posted pada UTANG
            row.posted=0
            save_request3(request, row)
            
            r = DBSession.query(AkJurnal.id).filter(AkJurnal.source_no==row.kode).first()
            #Menghapus Item Jurnal
            DBSession.query(AkJurnalItem).filter(AkJurnalItem.ak_jurnal_id==r).delete()
            DBSession.flush()
                
            #Menghapus UTANG yang sudah menjadi jurnal
            DBSession.query(AkJurnal).filter(AkJurnal.source_no==row.kode).delete()
            DBSession.flush()
            
        return route_list(request)
    return dict(row=row, form=form.render())
    
      
コード例 #11
0
ファイル: ap_invoice_skpd.py プロジェクト: aagusti/zosipkd
def view_delete(request):
    q = query_id(request)
    row = q.first()
    
    if not row:
        return id_not_found(request)
    if row.posted:
        request.session.flash('Data sudah diposting', 'error')
        return route_list(request)
    if row.status_spp:
        request.session.flash('Data sudah masuk di SPP', 'error')
        return route_list(request)
    if row.status_pay:
        request.session.flash('Data sudah masuk di Pembayaran Tagihan', 'error')
        return route_list(request)
    if row.amount:
        request.session.flash('Data tidak bisa dihapus, karena memiliki data items', 'error')
        return route_list(request)
        
    form = Form(colander.Schema(), buttons=('hapus','cancel'))
    values= {}
    if request.POST:
        if 'hapus' in request.POST:
            msg = '%s dengan kode %s telah berhasil.' % (request.title, row.kode)
            DBSession.query(APInvoice).filter(APInvoice.id==request.matchdict['id']).delete()
            DBSession.flush()
            request.session.flash(msg)
        return route_list(request)
    return dict(row=row, form=form.render())
コード例 #12
0
def preferences(request):
    schema = UserPreferencesSchema()
    button1 = Button('submit', _('Save changes'))
    button1.css_class = 'btn-primary'

    form = Form(schema, buttons=(button1, ))

    user = request.user

    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
        except ValidationFailure as e:
            return {'form': e.render()}

        user.update_preferences(appstruct)
        Session.add(user)

        request.session.flash(
            _('The changes were saved successfully'),
            'success',
        )
        return HTTPFound(location=request.route_path('user_preferences'))

    return {
        'form': form.render({
            'allow_google_analytics': user.allow_google_analytics,
            'send_passwords_periodically': user.send_passwords_periodically,
        })
    }
コード例 #13
0
ファイル: ar_sts.py プロジェクト: aagusti/o-sipkd
def view_delete(request):
    q = query_id(request)
    row = q.first()
    
    if not row:
        return id_not_found(request)
    if row.posted:
        request.session.flash('Data sudah diposting SKPD', 'error')
        return route_list(request)
    if row.posted1:
        request.session.flash('Data sudah diposting PPKD', 'error')
        return route_list(request)
    if row.nominal:
        request.session.flash('Data tidak bisa dihapus, karena memiliki data items', 'error')
        return route_list(request)
            
    form = Form(colander.Schema(), buttons=('hapus','cancel'))
    values= {}
    if request.POST:
        if 'hapus' in request.POST:
            msg = '%s dengan kode %s telah berhasil.' % (request.title, row.kode)
            DBSession.query(Sts).filter(Sts.id==request.matchdict['id']).delete()
            DBSession.flush()
            request.session.flash(msg)
        return route_list(request)
    return dict(row=row, form=form.render())
コード例 #14
0
def view_delete(request):
    q   = query_id(request)
    row = q.first()
    a   = row.id
	
    if not row:
        return id_not_found(request)
		
    # Seleksi untuk mengecek komentar
    i = DBSession.query(DisposisiComment).filter(DisposisiComment.disposisi_id==a).first()
    if i:
        request.session.flash('Hapus dahulu komentar pada surat masuk.', 'error')
        return route_list(request)
		
    # Seleksi untuk mengecek penerima
    b = DBSession.query(PenerimaDisposisi).filter(PenerimaDisposisi.disposisi_id==a).first()
    if b:
        request.session.flash('Hapus dahulu penerima.', 'error')
        return route_list(request)
        
    form = Form(colander.Schema(), buttons=('hapus','batal'))
    if request.POST:
        if 'hapus' in request.POST:
            msg = 'Surat masuk ID %d sudah dihapus.' % (row.id)
            q.delete()
            DBSession.flush()
            request.session.flash(msg)
        return route_list(request)
    return dict(row=row, form=form.render())
コード例 #15
0
def view_delete(request):
    q = query_id(request)
    row = q.first()
    uid = row.id
    
    if not row:
        return id_not_found(request)
        
    # Untuk mengecek apakah Rekening tersebut sedang dipakai oleh tabel lain. #    
    a = DBSession.query(Reklame).filter(Reklame.rekening_id==uid).first()
    if a:
        request.session.flash('Data tidak bisa dihapus, karena sudah masuk di Objek Pajak.', 'error')
        return route_list(request)
        
    b = DBSession.query(Jenis).filter(Jenis.rekening_id==uid).first()
    if b:
        request.session.flash('Data tidak bisa dihapus, karena sudah masuk di Jenis Reklame.', 'error')
        return route_list(request)
    #--------------------------------------------------------------------------------------------------------#    
    
    form = Form(colander.Schema(), buttons=('hapus','batal'))
    if request.POST:
        if 'hapus' in request.POST:
            msg = 'Rekening ID %d %s sudah dihapus.' % (row.id, row.nama)
            q.delete()
            DBSession.flush()
            request.session.flash(msg)
        return route_list(request)
    return dict(row=row, form=form.render())
コード例 #16
0
ファイル: auth.py プロジェクト: faddai/pyramidCrm
def login_view(request):
    """
        Login view
    """
    log.debug("# Login page")
    form = Form(authSchema,
                buttons=(Button(name="submit",
                                title="Valider",
                                type='submit'),))
    nextpage = request.params.get('nextpage') or request.route_url('index')
    app_struct = {'nextpage':nextpage}
    myform = form.render(app_struct)
    fail_message = None
    if 'submit' in request.params:
        log.debug(" + Validating authentication")
        controls = request.params.items()
        try:
            datas = form.validate(controls)
        except ValidationFailure, err:
            log.debug("Erreur d'authentification")
            myform = err.render()
            request.session.flash(_(request, u"Authentication error"), "error")
            return {'title':"Login page",
                    'form':myform,}
        log.debug("  + Validation ok, redirecting")
        log.debug("     -> {0}".format(nextpage))
        login = datas['login']
        # Storing the datas in the session
        remember(request, login)
        return HTTPFound(location=nextpage)
コード例 #17
0
class Three(Layouts):
        
    def __init__(self, context, request):
        super(Three, self).__init__(context, request)
        
        schema = GuestBookSchema().bind()
        button = Button(name="submit", title="Submit")
        self.form = Form(schema, buttons=(button,))
    
    @view_config(request_method="GET")
    def get(self):
        return {
            'form': self.form.render(),
            'js': self.form.get_widget_resources()['js'],
            'css': self.form.get_widget_resources()['css'],
            'comments': comments,
        }

    @view_config(request_method="POST", request_param="submit")
    def post(self):
        controls = self.request.POST.items()
        try:
            appstruct = self.form.validate(controls)
        except ValidationFailure as e:
            return {
                'form': e.render(),
                'js': self.form.get_widget_resources()['js'],
                'css': self.form.get_widget_resources()['css'],
                'comments': comments,
            }
        
        # So, obviously, in real life this would go in a database,
        # but I CBA, so I'm using a global value as my DB
        comments.append(appstruct)
        return {'form':'', 'comments':comments}
コード例 #18
0
ファイル: addlisting.py プロジェクト: trimastone/jobs
    def removeListing(self):
        """Deal with the listing removal page. The user is asked to give the reason they are removing
        the listing, then it is removed.
        """
        listing_id = self.request.matchdict.get('listing_id', None)

        if listing_id:
            listing = self.jobs_lib.getListingById(listing_id)
            if listing.user_id != self.request.authenticated_userid:
                return HTTPForbidden()

        myform = Form(removeSchema, buttons=('Remove Listing',))

        if self.request.method == 'POST':
            check_csrf_token(self.request)
            controls = self.request.POST.items()  # get the form controls

            try:
                appstruct = myform.validate(controls)  # call validate
            except deform.ValidationFailure as e:  # catch the exception
                return {'form':e.render()}  # re-render the form with an exception

            user = self.jobs_lib.getUserById(self.request.authenticated_userid)
            if not listing.removal_reason:
                self.jobs_lib.removeListing(user, listing, appstruct['removal_reason'])

            self.request.override_renderer = 'generic_message.mako'

            return dict(heading="Listing Removed",
                        messageList=["Your listing will no longer appear on the site.",
                                     "Thank you for using %s." % self.request.registry.settings['jobs.sitename']])
        else:
            appstruct = dict(csrf_token=self.request.session.get_csrf_token())
            return dict(form=myform.render(appstruct))
コード例 #19
0
ファイル: page.py プロジェクト: GunioRobot/ravel
def page_view(request):
    page_id = request.matchdict['page_id']
    page = request.context.page
    if not page:
        ## TODO: setup notfound view
        raise NotFound("No such page {0}".format(page_id))
    logged_in = authenticated_userid(request)
    api = get_template('ravel:templates/main.pt')
    commentschema = Comment()
    commentform = Form(commentschema,
                       action=route_url('comment_add', 
                                        request,
                                        page_id=page_id),
                       buttons=('submit',),
                       use_ajax=True)
    commentform['comment'].widget = widget.TextAreaWidget(rows=10, cols=60)
    print page.get('comments', None)
    return {
        'api' : api,
        'description' : page['description'],
        'edit_url' :  route_url('page_edit', request, page_id=page_id),
        'logged_in' : logged_in,
        'title' : page['title'],
        'body' : page['body'],
        'commentform' : commentform.render(),
        'comments' : page.get('comments', None)
        }
コード例 #20
0
def register_view(context, request):
    form = Form(Signup(), buttons=('register',))
    rendered_form = form.render(null)
    if 'register' in request.POST:
        try:
            appstruct = form.validate(request.POST.items())
        except ValidationFailure, e:
            rendered_form = e.render()
        else:
            pending = request.registry.queryAdapter(context, IRegistrations,
                                                    name='pending')
            if pending is None:  #pragma NO COVERAGE
                pending = PendingRegistrations(context)
            email = appstruct['email']
            token = getRandomToken(request)
            pending.set(email, token=token)

            from_addr = request.registry.settings['cartouche.from_addr']
            delivery = request.registry.queryUtility(IMailDelivery,
                                                     default=localhost_mta)
            confirmation_url = view_url(context, request, 'confirmation_url',
                                        'confirm_registration.html',
                                        email=email)
            body = REGISTRATION_EMAIL % {'token': token,
                                         'confirmation_url': confirmation_url}
            message = Message()
            message['Subject'] = 'Site registration confirmation'
            message.set_payload(body)
            delivery.send(from_addr, [email], message)
            return HTTPFound(location=confirmation_url)
コード例 #21
0
ファイル: views.py プロジェクト: tsauerwein/c2cgeoform
def edit(request):
    geo_form_schema = _get_schema(request)

    renderer = _get_renderer(geo_form_schema.templates_admin)
    form = Form(
        geo_form_schema.schema_admin, buttons=('submit',), renderer=renderer)
    _populate_widgets(form, DBSession)

    if 'submit' in request.POST:
        form_data = request.POST.items()

        try:
            obj_dict = form.validate(form_data)
        except ValidationFailure, e:
            rendered = e.render()
        else:
            obj = geo_form_schema.schema_admin.objectify(obj_dict)
            obj = DBSession.merge(obj)
            DBSession.flush()

            # FIXME create a fresh form, otherwise the IDs of objects in
            # relationships will not be rendered
            # see https://github.com/Pylons/deform/issues/236
            form = Form(
                geo_form_schema.schema_admin, buttons=('submit',),
                renderer=renderer)

            rendered = form.render(obj_dict)
コード例 #22
0
ファイル: ap_tbp.py プロジェクト: aagusti/zosipkd
 def view_ar_payment_item_delete(self):
     request = self.request
     q       = self.query_id()
     row     = q.first()
     
     if not row:
         return self.id_not_found(request)
     if row.posted:
         request.session.flash('Data sudah diposting', 'error')
         return self.route_list()
     if row.posted1:
         request.session.flash('Data sudah diposting rekap', 'error')
         return self.route_list()
         
     form = Form(colander.Schema(), buttons=('hapus','batal'))
     if request.POST:
         if 'hapus' in request.POST:
             msg = 'TBP ID %d %s sudah dihapus.' % (row.id, row.ref_nama)
             try:
               q.delete()
               DBSession.flush()
             except:
               msg = 'TBP ID %d %s tidak dapat dihapus.' % (row.id, row.ref_nama)
             request.session.flash(msg)
         return self.route_list()
     return dict(row=row, form=form.render())
コード例 #23
0
def view_delete(request):
    q = query_id(request)
    row = q.first()
    x   = row.approval_level
    a   = row.product_plan_id
	
    if not row:
        return id_not_found(request)
    if x == 2: 
        request.session.flash('Data tidak dapat dihapus, karena sudah disetujui.', 'error')
        return route_list(request)
		
    form = Form(colander.Schema(), buttons=('hapus','batal'))
    if request.POST:
        if 'hapus' in request.POST:
            msg = 'Approval rencana ID %d sudah dihapus.' % (row.id)
            q.delete()
            DBSession.flush()
            request.session.flash(msg)
			
            r = DBSession.query(ProductPlan).filter(ProductPlan.id==a).first()   
            r.approval_level = 0
            r.disabled       = 0
            save_request2(r)
	
        return route_list(request)
    return dict(row=row, form=form.render())
コード例 #24
0
ファイル: ap_payment.py プロジェクト: aagusti/zosipkd
def view_delete(request):
    q = query_id(request)
    row = q.first()
    
    if not row:
        return id_not_found(request)
    if row.posted:
        request.session.flash('Data sudah diposting', 'error')
        return route_list(request)
    if row.status_spp:
        request.session.flash('Data sudah di SPP', 'error')
        return route_list(request)
    """
    if row.amount:
        request.session.flash('Data tidak bisa dihapus, karena memiliki data items', 'error')
        return route_list(request)
    """    
    form = Form(colander.Schema(), buttons=('hapus','cancel'))
    values= {}
    if request.POST:
        if 'hapus' in request.POST:
            msg = '%s dengan kode %s telah berhasil.' % (request.title, row.kode)
            DBSession.query(APPayment).filter(APPayment.id==request.matchdict['id']).delete()
            DBSession.flush()
            request.session.flash(msg)
            
            #Untuk update status posted dan status_pay pada APInvoice
            inv_id = row.invoice_id
            row = DBSession.query(APInvoice).filter(APInvoice.id==inv_id).first()   
            row.status_pay = 0
            save_request2(row)
    
        return route_list(request)
    return dict(row=row, form=form.render())
    
コード例 #25
0
ファイル: views.py プロジェクト: WasatchPhotonics/CookBook
    def checkout_add(self):
        """ Show an empty form, or on submit, store the validated
        information in the db.
        """
        form = Form(NewFormSchema(), buttons=("submit",))
        if "submit" in self.request.POST:
            #log.info("All request: %s", self.request.environ)

            #log.info("Submit: %s", self.request.POST)
            controls = self.request.POST.items()

            try:
                appstruct = form.validate(controls)

                # write uploads to disk, save to db
                chk_id = self.add_to_database(appstruct)
                self.generate_qr_label(appstruct, chk_id)
                self.generate_calibration_report(appstruct, chk_id)
                self.generate_placeholder_thumbnails(chk_id)

                location = self.request.route_url("checkout_view",
                                                  checkout_id=chk_id)
                return HTTPFound(location=location)

            except ValidationFailure as exc:
                #log.warn("Validation failure")
                return {"form":exc.render()}

        return {"form":form.render()}
コード例 #26
0
ファイル: views.py プロジェクト: WasatchPhotonics/CookBook
    def file_add(self):
        """ Expect a valid checkout id, add a file to the file system
        and store retrieval values in database.
        """
        # require a known checkout id
        checkout_id = self.request.matchdict["checkout_id"]
        dbqry = DBSession.query(Checkout)
        checkout = dbqry.filter(Checkout.id == checkout_id).one()

        form = Form(NewFileSchema(), buttons=("submit",))
        if "submit" in self.request.POST:
            log.info("File submit: %s", self.request.POST)
            controls = self.request.POST.items()

            try:
                appstruct = form.validate(controls)

                self.assign_filename_if_selected(appstruct)
                chk_id = self.file_add_to_database(appstruct)
                self.explode_work_ticket(appstruct, chk_id)
                self.cache_thumbnails(appstruct, chk_id)

                location = self.request.route_url("checkout_view",
                                                  checkout_id=chk_id)
                return HTTPFound(location=location)

            except ValidationFailure as exc:
                log.warn("File Validation failure")
                checkout = {"serial":"invalid", "id":"invalid",
                            "timestamp":"invalid"}
                return {"form":exc.render(), "checkout":checkout}

        return {"form":form.render(), "checkout":checkout}
コード例 #27
0
ファイル: ap_sp2d.py プロジェクト: aagusti/osipkd-pdpt
 def view_delete(self):
     q = self.query_id()
     row = q.first()
     request=self.request
     
     if not row:
         return id_not_found(request)
     if row.posted:
         request.session.flash('Data sudah diposting', 'error')
         return self.route_list()
     if row.status_giro:
         request.session.flash('Data masih terdapat pada Giro', 'error')
         return self.route_list()
         
     form = Form(colander.Schema(), buttons=('hapus','cancel'))
     values= {}
     if request.POST:
         if 'hapus' in request.POST:
         
             #Untuk menghapus SP2D
             msg = '%s dengan kode %s telah berhasil.' % (request.title, row.kode)
             DBSession.query(Sp2d).filter(Sp2d.id==request.matchdict['id']).delete()
             DBSession.flush()
             request.session.flash(msg)
             
             #Untuk update status posted dan disabled pada SPM
             row = DBSession.query(Spm).filter(Spm.id==row.ap_spm_id).first()   
             row.posted=0
             row.disabled=0
             self.save_request3(row)
             
         return self.route_list()
     return dict(row=row,form=form.render())
コード例 #28
0
ファイル: contest.py プロジェクト: bertjwregeer/defcne
    def edit(self):
        contest = self.context.contest

        e = {}
        e['name'] = contest.disp_name
        e['url'] = {}
        e['url']['manage'] = self.request.route_url('defcne.c', traverse=(contest.dc, contest.id, 'manage'))
        e['url']['edit'] = self.request.route_url('defcne.c', traverse=(contest.dc, contest.id, 'edit'))
        e['url']['extrainfo'] = self.request.route_url('defcne.c', traverse=(contest.dc, contest.id, 'extrainfo'))

        astruct = contest.to_appstruct()
        astruct['name'] = astruct['disp_name']

        (schema, f) = ContestForm.create_form(request=self.request,
                action=self.request.current_route_url(), type='contest', origname=contest.name)

        if contest.logo:
            schema['logo'].description = "A logo has already been uploaded. Uploading a new logo will overwrite the previous logo!"
        del astruct['logo']
        del schema['ticket']

        f = Form(schema, action=self.request.current_route_url(), buttons=('submit',))

        return {
                'page_title': 'Edit Contest: {}'.format(contest.disp_name),
                'cve': e,
                'form': f.render(astruct),
                'type': 'contest',
                }
コード例 #29
0
def view_delete(request):
    q = query_id(request)
    row = q.first()
    uid = row.id
    
    if not row:
        return id_not_found(request)
        
    a = DBSession.query(Kelurahan).filter(Kelurahan.kecamatan_id==uid).first()
    if a:
        request.session.flash('Data tidak bisa dihapus, karena sudah masuk di Tabel Kelurahan.', 'error')
        return route_list(request)
        
    b = DBSession.query(Reklame).filter(Reklame.kecamatan_id==uid).first()
    if b:
        request.session.flash('Data tidak bisa dihapus, karena sudah masuk di Tabel Objek Pajak.', 'error')
        return route_list(request)
        
    form = Form(colander.Schema(), buttons=('hapus','batal'))
    if request.POST:
        if 'hapus' in request.POST:
            msg = 'Kecamatan ID %d %s sudah dihapus.' % (row.id, row.nama)
            q.delete()
            DBSession.flush()
            request.session.flash(msg)
        return route_list(request)
    return dict(row=row,form=form.render())
コード例 #30
0
ファイル: views_auth.py プロジェクト: d9k/pyragrid
    def view_register(self):

        # def validate_register(form, values):
        #     pass

        register_form = Form(
            RegisterSchema(
                # validator=validate_register
            ).bind(),
            buttons=[Button(name='register_form_submit', title='Зарегистрировать')]
        )

        if 'register_form_submit' in self.request.params:
            controls = self.request.POST.items()
            try:
                data = register_form.validate(controls)
            except deform.ValidationFailure as e:
                r = e.render()
                return dict(rendered_register_form=r)

            # TODO create new user

            # new_user = User(login='******', name='Дмитрий Комаров', email='*****@*****.**')

            new_user = User()
            dictalchemy.utils.fromdict(new_user, data)
            self.request.session.invalidate()
            # TODO check user.beforeSave() is called before save
            # if not new_user.name:
            #     new_user.name = new_user.login
            password = data.get('password')
            if not password:
                password = User.generate_password()
                self.request.session['new_password'] = password
            new_user.set_password(password)
            try:
                with transaction.manager:
                    DBSession.add(new_user)
            except DBAPIError:
                return Response(conn_err_msg, content_type='text/plain', status_int=500)

            helpers.send_html_mail(new_user.email, 'registered',
                                   {'user_name': new_user.name, 'password': password})

            new_user.initiate_email_check()
            try:
                with transaction.manager:
                    DBSession.add(new_user)
            except DBAPIError:
                return Response(conn_err_msg, content_type='text/plain', status_int=500)

            self.request.session['new_user_id'] = new_user.id
            success_location = self.request.route_url('register_success')
            return HTTPFound(location=success_location)

        return dict(rendered_register_form=register_form.render())
コード例 #31
0
def edit_account_view(context, request):
    confirmed = request.registry.queryAdapter(context,
                                              IRegistrations,
                                              name='confirmed')
    if confirmed is None:  #pragma NO COVERAGE
        confirmed = ConfirmedRegistrations(context)

    identity = request.environ.get('repoze.who.identity')
    if identity is None:
        return HTTPUnauthorized()

    userid = identity['repoze.who.userid']
    account_info = confirmed.get(userid)
    if account_info is None:
        return HTTPForbidden()

    appstruct = {
        'login_name': account_info.login,
        'email': account_info.email,
        'security': {
            'question': account_info.security_question or '',
            'answer': account_info.security_answer or '',
        },
    }
    schema = EditAccount().bind(current_login_name=account_info.login,
                                confirmed=confirmed,
                                old_password=account_info.password)
    form = Form(schema, buttons=('update', ))
    rendered_form = form.render(appstruct)

    if 'update' in request.POST:
        try:
            appstruct = form.validate(request.POST.items())
        except ValidationFailure, e:
            rendered_form = e.render()
        else:
            login = appstruct['login_name']
            email = appstruct['email']
            pwd_mgr = SSHAPasswordManager()
            password = pwd_mgr.encodePassword(appstruct['password'])
            security_question = appstruct['security']['question']
            security_answer = appstruct['security']['answer']
            confirmed.set(
                userid,
                email=email,
                login=login,
                password=password,
                security_question=security_question,
                security_answer=security_answer,
            )
            return HTTPFound(location=view_url(
                context,
                request,
                'after_edit_url',
                request.view_name,
            ))
コード例 #32
0
    def site_view(self):
        def refresh_cache():
            # we simply remove all cached files
            cache_directory = real_path(CACHE_SUBDIRECTORY)
            if os.path.exists(cache_directory):
                for fn in os.listdir(cache_directory):
                    shutil.rmtree(os.path.join(cache_directory, fn))

        schema = Configuration()
        settings = get_current_registry().settings

        def get_some_scan(request):
            result = request.solr_scan.search(q='*:*', rows=1)
            if not result.documents:
                return None
            doc = result.documents[0]
            url = request.route_url('service_scan_images_item',
                                    number=str(doc['number']),
                                    number_of_image=doc['default_image_id'])
            image_url = os.path.join(
                url, 'file_%s' % str(hash(doc['dateLastModified'])))
            return image_url

        example_image = ''

        default_values = [(node.name, unicode(settings.get(node.name, 'xxx')))
                          for node in schema.children]
        form = Form(schema, buttons=('submit', ))
        if self.request.POST:
            controls = self.request.POST.items()
            try:
                appstruct = form.validate(controls)
            except ValidationFailure, e:
                return {'form': e.render(), 'example_image': example_image}

            # Process the valid form data, do some work
            # if the file does not exist, we raise a validation error
            if appstruct['watermark_file'] and not os.path.exists(
                    appstruct['watermark_file']):
                raise HTTPBadRequest(
                    'This file {watermark_file} cannot be found'.format(
                        **appstruct))
            # if anything has changed, we reset the cache
            for key in appstruct:
                if settings.get(key) != appstruct[key]:
                    refresh_cache()
                    continue

            for key in appstruct:
                # save the new settings in the database
                self.set_setting(self.request, key, appstruct[key])

            # update the global settings object with our new values
            settings.update(appstruct)
            example_image = get_some_scan(self.request)
            return {"form": form.render(), 'example_image': example_image}
コード例 #33
0
ファイル: views.py プロジェクト: norsig/yith-library-server
def destroy(request):
    schema = AccountDestroySchema()
    button1 = Button('submit', _('Yes, I am sure. Destroy my account'))
    button1.css_class = 'btn-danger'
    button2 = Button('cancel', _('Cancel'))
    button2.css_class = 'btn-default'

    form = Form(schema, buttons=(button1, button2))

    user = request.user

    can_destroy = len(user.applications) == 0

    context = {
        'passwords': len(user.passwords),
        'can_destroy': can_destroy,
    }

    if 'submit' in request.POST:

        if not can_destroy:
            request.session.flash(
                _('You must remove your applications before destroying your account'
                  ),
                'error',
            )
            return HTTPFound(
                location=request.route_path('oauth2_developer_applications'))

        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
        except ValidationFailure as e:
            context['form'] = e.render()
            return context

        reason = appstruct['reason']
        notify_admins_of_account_removal(request, user, reason)

        Session.delete(user)

        request.session.flash(
            _('Your account has been removed. Have a nice day!'),
            'success',
        )
        return logout(request)

    elif 'cancel' in request.POST:
        request.session.flash(
            _('Thanks for reconsidering removing your account!'),
            'info',
        )
        return HTTPFound(location=request.route_path('user_information'))

    context['form'] = form.render()
    return context
コード例 #34
0
    def view(self):
        # Get LDAP settings
        ldap_settings = self.request.db.ldap.find_one()
        if ldap_settings is None:
            ldap_settings = dict()

        # Generate form
        from phoenix.settings.schema import LdapSchema
        ldap_form = Form(schema=LdapSchema().bind(request=self.request), buttons=('submit',), formid='deform')

        if 'submit' in self.request.params:
            check_csrf_token(self.request)
            try:
                # Validate form
                appstruct = ldap_form.validate(list(self.request.params.items()))
            except ValidationFailure as e:
                LOGGER.exception('Validation failed!')
                return dict(title='LDAP Settings', form=e.render())
            else:
                # Update LDAP settings
                ldap_settings['server'] = appstruct['server']
                ldap_settings['use_tls'] = appstruct['use_tls']
                ldap_settings['bind'] = appstruct['bind']
                ldap_settings['passwd'] = appstruct['passwd']
                ldap_settings['base_dn'] = appstruct['base_dn']
                ldap_settings['filter_tmpl'] = appstruct['filter_tmpl']
                ldap_settings['scope'] = appstruct['scope']
                # Optional:
                ldap_settings['name'] = appstruct['name']
                ldap_settings['email'] = appstruct['email']
                self.request.db.ldap.save(ldap_settings)

                import ldap
                if ldap_settings['scope'] == 'ONELEVEL':
                    ldap_scope = ldap.SCOPE_ONELEVEL
                else:
                    ldap_scope = ldap.SCOPE_SUBTREE

                from pyramid.config import Configurator
                config = Configurator(registry=self.request.registry)
                config.ldap_setup(
                    ldap_settings['server'],
                    bind=ldap_settings['bind'],
                    passwd=ldap_settings['passwd'],
                    use_tls=ldap_settings['use_tls'])
                config.ldap_set_login_query(
                    base_dn=ldap_settings['base_dn'],
                    filter_tmpl=ldap_settings['filter_tmpl'],
                    scope=ldap_scope)
                config.commit()

                self.session.flash('Successfully updated LDAP settings!', queue='success')

        # Display form
        return dict(title='LDAP Settings', form=ldap_form.render(ldap_settings))
コード例 #35
0
ファイル: views.py プロジェクト: norsig/yith-library-server
def contact(request):
    button1 = Button('submit', _('Send message'))
    button1.css_class = 'btn-primary'
    button2 = Button('cancel', _('Cancel'))
    button2.css_class = 'btn-default'

    form = Form(ContactSchema(), buttons=(button1, button2))

    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
        except ValidationFailure as e:
            return {'form': e.render()}

        context = {'link': request.route_url('contact')}
        context.update(appstruct)
        subject = ("%s sent a message from Yith's contact form" %
                   appstruct['name'])

        result = send_email_to_admins(
            request,
            'yithlibraryserver:templates/email_contact',
            context,
            subject,
            extra_headers={'Reply-To': appstruct['email']},
        )

        if result is None:
            log.error(
                '%s <%s> tried to send a message from the contact form but no '
                'admin emails were configured. Message: %s' % (
                    appstruct['name'],
                    appstruct['email'],
                    appstruct['message'],
                ))

        request.session.flash(
            _('Thank you very much for sharing your opinion'),
            'info',
        )

        return HTTPFound(location=request.route_path('home'))

    elif 'cancel' in request.POST:
        return HTTPFound(location=request.route_path('home'))

    initial = {}
    if request.user is not None:
        initial['name'] = request.user.first_name
        if request.user.email_verified:
            initial['email'] = request.user.email

    return {'form': form.render(initial)}
コード例 #36
0
ファイル: views.py プロジェクト: dholth/sharder
def edit_slideshow(request):
    context = request.context
    form = Form(schema.Slideshow(), buttons=('submit', ))
    appstruct = {
        'name':
        context.name,
        'slides': [
            dict(shard=slide.shard_id, duration=slide.duration)
            for slide in context.slides
        ]
    }
    return {'form': form.render(appstruct), 'title': u'Edit Slideshow'}
コード例 #37
0
def get_form(config,mwf):
    from nipype.interfaces.traits_extension import isdefined
    if not isdefined(mwf.html_view):
        schema = colander.Schema()    
        all_traits = config.trait_names()  
        all_traits.remove('trait_added')
        all_traits.remove('trait_modified')
     
        for tr in all_traits:
            _type = type(config.trait(tr).trait_type)
        
            col_type = getNode(_type,tr,config)    
        
            schema.add(col_type)
    
        form = Form(schema,buttons = ('submit',),action='')   
    
        return form.render(appstruct=config.get())
    else:
        form = Form(mwf.html_view(),buttons = ('submit',),action='')
        return form.render()
コード例 #38
0
def view_delete(request):
    q = query_id(request)
    row = q.first()
    a = row.id
    x = row.approval_level

    if not row:
        return id_not_found(request)
    if x == 1:
        request.session.flash(
            'Data tidak dapat dihapus, karena sudah masuk di Menu Approval.',
            'error')
        return route_list(request)
    if x == 2:
        request.session.flash(
            'Data tidak dapat dihapus, karena sudah disetujui.', 'error')
        return route_list(request)
    if row.disabled:
        request.session.flash(
            'Data tidak dapat dihapus, karena sudah masuk di Menu Approval.',
            'error')
        return route_list(request)
    if row.status_dlv:
        request.session.flash(
            'Data tidak dapat dihapus, karena sudah masuk di Menu Pengiriman Gudang.',
            'error')
        return route_list(request)

    # Seleksi untuk di menu Approval
    r = DBSession.query(ProductReqAppr).filter(
        ProductReqAppr.product_request_id == a).first()
    if r:
        request.session.flash(
            'Hapus dahulu data rencana yang sudah pernah dibuat di Menu Approval.',
            'error')
        return route_list(request)

    # Seleksi untuk mengecek item
    i = DBSession.query(ProductRequestItem).filter(
        ProductRequestItem.product_request_id == a).first()
    if i:
        request.session.flash('Hapus dahulu item produk / barang.', 'error')
        return route_list(request)

    form = Form(colander.Schema(), buttons=('hapus', 'batal'))
    if request.POST:
        if 'hapus' in request.POST:
            msg = 'Order ID %d sudah dihapus.' % (row.id)
            q.delete()
            DBSession.flush()
            request.session.flash(msg)
        return route_list(request)
    return dict(row=row, form=form.render())
コード例 #39
0
ファイル: views.py プロジェクト: sanderkr/todopyramid
 def account_view(self):
     """This is the settings form for the user. The first time a
     user logs in, they are taken here so we can get their first and
     last name.
     """
     # Special case when the db was blown away
     if self.user_id is not None and self.user is None:
         return self.logout()
     section_name = 'account'
     schema = SettingsSchema()
     form = Form(schema, buttons=('submit', ))
     css_resources, js_resources = self.form_resources(form)
     if 'submit' in self.request.POST:
         controls = self.request.POST.items()
         try:
             form.validate(controls)
         except ValidationFailure as e:
             msg = 'There was an error saving your settings.'
             self.request.session.flash(msg, queue='error')
             return {
                 'form': e.render(),
                 'css_resources': css_resources,
                 'js_resources': js_resources,
                 'section': section_name,
             }
         values = parse(self.request.params.items())
         # Update the user
         with transaction.manager:
             self.user.first_name = values.get('first_name', u'')
             self.user.last_name = values.get('last_name', u'')
             self.user.time_zone = values.get('time_zone', u'US/Eastern')
             DBSession.add(self.user)
         self.request.session.flash(
             'Settings updated successfully',
             queue='success',
         )
         return HTTPFound('/list')
     # Get existing values
     if self.user is not None:
         appstruct = dict(
             first_name=self.user.first_name,
             last_name=self.user.last_name,
             time_zone=self.user.time_zone,
         )
     else:
         appstruct = {}
     return {
         'form': form.render(appstruct),
         'css_resources': css_resources,
         'js_resources': js_resources,
         'section': section_name,
     }
コード例 #40
0
def view_admin(request):
    id_ = request.matchdict['id']
    geo_form_schema = _get_schema(request)
    renderer = _get_renderer(geo_form_schema.templates_admin)
    form = Form(geo_form_schema.schema_admin, buttons=('submit',),
                renderer=renderer)
    obj = DBSession.query(geo_form_schema.model).get(id_)
    rendered = form.render(geo_form_schema.schema_admin.dictify(obj),
                           readonly=True, request=request)
    return {
        'form': rendered,
        'schema': geo_form_schema,
        'deform_dependencies': form.get_widget_resources()}
コード例 #41
0
def register(context, request):
    schema = RegisterSchema().bind(request=request)
    form = Form(schema, buttons=(Button('register', _(u'Register')), ))
    rendered_form = None

    if 'register' in request.POST:
        try:
            appstruct = form.validate(request.POST.items())
        except ValidationFailure as e:
            request.session.flash(_(u"There was an error."), 'error')
            rendered_form = e.render()
        else:
            settings = get_settings()

            appstruct['groups'] = u''
            appstruct['roles'] = u''

            register_groups = settings['kotti.register.group']
            if register_groups:
                appstruct['groups'] = [register_groups]

            register_roles = settings['kotti.register.role']
            if register_roles:
                appstruct['roles'] = {'role:' + register_roles}

            appstruct['send_email'] = True
            form = UserAddFormView(context, request)
            form.add_user_success(appstruct)
            success_msg = _(
                'Congratulations! You are successfully registered. '
                'You should be receiving an email with a link to set your '
                'password. Doing so will activate your account.')
            request.session.flash(success_msg, 'success')
            name = appstruct['name']
            notify(UserSelfRegistered(get_principals()[name], request))
            return HTTPFound(location=request.application_url)

    if rendered_form is None:
        rendered_form = form.render(request.params)

    api = template_api(
        context,
        request,
        page_title=_(u"Register - ${title}",
                     mapping=dict(title=context.title)),
    )

    return {
        'api': api,
        'form': rendered_form,
    }
コード例 #42
0
def view_delete(request):
    q = query_id(request)
    row = q.first()
    if not row:
        return id_not_found(request)
    form = Form(colander.Schema(), buttons=('hapus', 'batal'))
    if request.POST:
        if 'hapus' in request.POST:
            msg = 'Urusan ID %d %s sudah dihapus.' % (row.id, row.nama)
            q.delete()
            DBSession.flush()
            request.session.flash(msg)
        return route_list(request)
    return dict(row=row, form=form.render())
コード例 #43
0
def view_delete(request):
    q = query_id(request)
    row = q.first()
    if not row:
        return id_not_found(request)
    form = Form(colander.Schema(), buttons=('delete', 'cancel'))
    if request.POST:
        if 'delete' in request.POST:
            msg = 'Rekon E-PAP ID %d berhasil dihapus.' % (row.id)
            q.delete()
            DBSession.flush()
            request.session.flash(msg)
        return route_list(request)
    return dict(row=row, form=form.render())
コード例 #44
0
ファイル: user.py プロジェクト: aagusti/osipkd-json-rpc
def view_delete(request):
    q = query_id(request)
    row = q.first()
    if not row:
        return id_not_found(request)
    form = Form(colander.Schema(), buttons=('delete','cancel'))
    if request.POST:
        if 'delete' in request.POST:
            msg = 'User ID %d %s has been deleted.' % (row.id, row.email)
            q.delete()
            DBSession.flush()
            request.session.flash(msg)
        return route_list(request)
    return dict(row=row,
                 form=form.render())
コード例 #45
0
def view_delete(request):
    q = query_id(request)
    row = q.first()
    if not row:
        return id_not_found(request)
    form = Form(colander.Schema(), buttons=('hapus', 'batal'))
    if request.POST:
        if 'hapus' in request.POST:
            msg = 'User ID {user_id} {email} {user_name} berhasil dihapus.'.format(
                user_id=row.id, email=row.email, user_name=row.user_name)
            q.delete()
            DBSession.flush()
            request.session.flash(msg)
        return route_list(request)
    return dict(row=row, form=form.render())
コード例 #46
0
ファイル: views.py プロジェクト: pauleveritt/scratchpad
 def add_folder(self):
     schema = FolderSchema()
     form = Form(schema, buttons=('submit', ))
     if 'submit' in self.request.POST:
         # Make a new Folder
         title = self.request.POST['title']
         name = str(randint(0, 999999))
         new_folder = Folder(title)
         new_folder.__name__ = name
         new_folder.__parent__ = self.context
         self.context[name] = new_folder
         # Redirect to the new folder
         url = self.request.resource_url(new_folder)
         return HTTPFound(location=url)
     return {"form": form.render()}
コード例 #47
0
ファイル: groupperm.py プロジェクト: pinguin999/web-register
def view_delete(request):
    q = query_id(request)
    row = q.first()
    if not row:
        return id_not_found(request)
    form = Form(colander.Schema(), buttons=('delete', 'cancel'))
    if request.POST:
        if 'delete' in request.POST:
            msg = 'Group %s Route ID %s sudah dihapus.' % (
                row.groups.group_name, row.routes.nama)
            q.delete()
            DBSession.flush()
            request.session.flash(msg)
        return route_list(request)
    return dict(row=row, form=form.render())
コード例 #48
0
ファイル: login.py プロジェクト: timgates42/Kotti
def register(context, request):
    schema = RegisterSchema().bind(request=request)
    form = Form(schema, buttons=(Button("register", _("Register")),))
    rendered_form = None

    if "register" in request.POST:
        try:
            appstruct = form.validate(request.POST.items())
        except ValidationFailure as e:
            request.session.flash(_("There was an error."), "error")
            rendered_form = e.render()
        else:
            settings = get_settings()

            appstruct["groups"] = ""
            appstruct["roles"] = ""

            register_groups = settings["kotti.register.group"]
            if register_groups:
                appstruct["groups"] = [register_groups]

            register_roles = settings["kotti.register.role"]
            if register_roles:
                appstruct["roles"] = {"role:" + register_roles}

            appstruct["send_email"] = True
            form = UserAddFormView(context, request)
            form.add_user_success(appstruct)
            success_msg = _(
                "Congratulations! You are successfully registered. "
                "You should be receiving an email with a link to set your "
                "password. Doing so will activate your account."
            )
            request.session.flash(success_msg, "success")
            name = appstruct["name"]
            notify(UserSelfRegistered(get_principals()[name], request))
            return HTTPFound(location=request.application_url)

    if rendered_form is None:
        rendered_form = form.render(request.params)

    api = template_api(
        context,
        request,
        page_title=_("Register - ${title}", mapping=dict(title=context.title)),
    )

    return {"api": api, "form": rendered_form}
コード例 #49
0
ファイル: views.py プロジェクト: pauleveritt/scratchpad
 def add_document(self):
     schema = DocumentSchema()
     form = Form(schema, buttons=('submit', ))
     if 'submit' in self.request.POST:
         # Make a new Document
         title = self.request.POST['title']
         content = self.request.POST['content']
         name = str(randint(0, 999999))
         new_document = Document(title, content)
         new_document.__name__ = name
         new_document.__parent__ = self.context
         self.context[name] = new_document
         # Redirect to the new document
         url = self.request.resource_url(new_document)
         return HTTPFound(location=url)
     return {"form": form.render()}
コード例 #50
0
ファイル: group.py プロジェクト: aagusti/geo
def view_delete(request):
    q = query_id(request)
    row = q.first()
    if not row:
        return id_not_found(request)
    form = Form(colander.Schema(), buttons=('delete','cancel'))
    if request.POST:
        if 'delete' in request.POST:
            msg = 'Group ID {id} {name} has been deleted.'.format(
                    id=row.id, name=row.group_name)
            q.delete()
            DBSession.flush()
            request.session.flash(msg)
        return route_list(request)
    return dict(row=row,
                 form=form.render())
コード例 #51
0
    def site_view(self):
        schema = Person()
        myform = Form(schema, buttons=('submit', ))

        if 'submit' in self.request.POST:
            controls = self.request.POST.items()
            try:
                appstruct = myform.validate(controls)
            except ValidationFailure, e:
                return {'form': e.render(), 'values': False}
            # Process the valid form data, do some work
            values = {
                "name": appstruct['name'],
                "shoe_size": appstruct['shoe_size'],
            }
            return {"form": myform.render(), "values": values}
コード例 #52
0
    def show(self, form):
        # re-validate form, it is possible to be changed
        appstruct = {}
        controls = list(self.request.POST.items())

        if controls:
            try:
                appstruct = form.validate(controls)
            except deform.exception.ValidationFailure as e:
                return self.failure(e)

        schema = form.schema
        # now add new schemas, at the end of all others
        add_component = appstruct.pop('pipeline_components', None)

        if add_component:
            p = pipeline_registry[add_component]
            s = p.schema(name=rand(10), title=p.title,)
            schema.add(s)
            # move pipeline_components to the bottom
            w = schema.__delitem__('pipeline_components')
            schema.add(w)

        # try to build a preview, if possible

        if appstruct.get('column'):
            pipeline = self.pipeline_from_schema(schema, appstruct)
            pstruct = self.request.create_corpus_pipeline_struct = {
                'file_name': self.document,
                'text_column': appstruct['column'],
                'pipeline': pipeline,
                'preview_mode': True
            }
            content_stream = build_pipeline(**pstruct)

            self.preview = islice(content_stream, 0, self.preview_size)

        form = Form(schema, buttons=self.buttons, renderer=deform_renderer,
                    **dict(self.form_options))
        reqts = form.get_widget_resources()

        return {
            'form': form.render(appstruct),
            'css_links': reqts['css'],
            'js_links': reqts['js'],
        }
コード例 #53
0
ファイル: F160401.py プロジェクト: aagusti/opensipkd-piutang
    def view_delete(self):
        request = self.req
        id = request.matchdict['id']
        q = query_id(request)
        row = q.first()
        if not row:
            return id_not_found(request)

        form = Form(colander.Schema(), buttons=('reversal', 'batal'))
        if request.POST:
            if 'reversal' in request.POST:
                msg = 'Pembayaran ID %s senilai %s berhasil dibatalkan.' % (
                    id, row.jml_sppt_yg_dibayar)
                PembayaranSppt.reversal(id)
                request.session.flash(msg)
            return route_list(request)
        return dict(project=self.project, row=row, id=id, form=form.render())
コード例 #54
0
ファイル: views.py プロジェクト: norsig/yith-library-server
def user_information(request):
    schema = UserSchema()
    button1 = Button('submit', _('Save changes'))
    button1.css_class = 'btn-primary'

    form = Form(schema, buttons=(button1, ))

    user = request.user

    if 'submit' in request.POST:

        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
        except ValidationFailure as e:
            return {'form': e.render()}

        changes = {
            'first_name': appstruct['first_name'],
            'last_name': appstruct['last_name'],
            'screen_name': appstruct['screen_name'],
            'email': appstruct['email']['email'],
        }
        user.update_user_info(changes)

        Session.add(user)

        request.session.flash(
            _('The changes were saved successfully'),
            'success',
        )
        return HTTPFound(location=request.route_path('user_information'))

    return {
        'form':
        form.render({
            'first_name': user.first_name,
            'last_name': user.last_name,
            'screen_name': user.screen_name,
            'email': {
                'email': user.email,
                'email_verified': user.email_verified,
            },
        }),
    }
コード例 #55
0
ファイル: views.py プロジェクト: VoteIT/voteit.cloudsignon
def twitter_login_complete(context, request):
    result = {
        'profile': context.profile,
        'credentials': context.credentials,
    }

    schema = createSchema('CSORegisterUserSchema').bind(context=context,
                                                        request=request)
    form = Form(schema,
                action='/twitter_register',
                buttons=(button_register, ))

    oauth_token = result['credentials']['oauthAccessToken']
    oauth_userid = result['profile']['accounts'][0]['userid']

    if 'displayName' in result['profile']:
        userid = result['profile']['displayName']
    else:
        userid = ''
    if 'name' in result['profile']:
        first_name = result['profile']['name']['givenName']
        last_name = result['profile']['name']['familyName']
    else:
        first_name = ''
        last_name = ''
    if 'verifiedEmail' in result['profile']:
        email = result['profile']['verifiedEmail']
    else:
        email = ''

    if not NEW_USERID_PATTERN.match(userid):
        userid = ''

    appstruct = {
        'userid': userid,
        'oauth_access_token': oauth_token,
        'oauth_userid': oauth_userid,
        'first_name': first_name,
        'last_name': last_name,
        'email': email,
    }
    appstruct['came_from'] = request.session.get('came_from', '')
    del request.session['came_from']

    return {'form': form.render(appstruct=appstruct)}
コード例 #56
0
ファイル: sidebars.py プロジェクト: zhangqiang99/voteit.core
def login_box(context, request, va, **kwargs):
    api = kwargs['api']
    if api.userid or request.path_url.endswith('/login'):
        return u""
    #FIXME: Ticket system makes it a bit of a hassle to make login detached from registration.
    #We'll do that later. For now, let's just check if user is on login or registration page
    login_schema = createSchema('LoginSchema').bind(context=context,
                                                    request=request)
    action_url = request.resource_url(api.root, 'login')
    login_form = Form(login_schema,
                      buttons=(button_login, ),
                      action=action_url)
    api.register_form_resources(login_form)
    response = dict(
        api=api,
        form=login_form.render(),
    )
    return render('templates/sidebars/login_pw.pt', response, request=request)
コード例 #57
0
ファイル: views.py プロジェクト: Rich43/deformtest
def form_view(request):
    schema = EditMenuItems()
    myform = Form(schema, buttons=('submit', ))
    reqt = myform.get_widget_resources(myform.get_widget_requirements())
    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            myform.validate(controls)

        except ValidationFailure as e:
            return {'form': e.render()}
        return {'form': 'OK'}
    return {
        'form': myform.render(),
        'project': 'poop',
        'css': reqt['css'],
        'js': reqt['js']
    }
コード例 #58
0
def view_delete(request):
    q = query_id(request)
    row = q.first()
    if not row:
        return id_not_found(request)
    form = Form(colander.Schema(), buttons=('delete', 'cancel'))
    values = {}
    if request.POST:
        if 'delete' in request.POST:
            values['id'] = request.matchdict['id']
            msg = 'Rekening ID %s OPD %s sudah di hapus.' % (
                row.rekenings.kode, row.units.kode)
            row = DBSession.query(UnitRekening).filter(UnitRekening.id==values['id'])\
                      .delete()
            DBSession.flush()
            request.session.flash(msg)
        return route_list(request)
    return dict(row=row, form=form.render())
コード例 #59
0
def form_view(request):
    schema = UserSchema()
    myform = Form(schema, buttons=('submit', ))
    template_values = {}
    template_values.update(myform.get_widget_resources())

    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            myform.validate(controls)
        except ValidationFailure as e:
            template_values['form'] = e.render()
        else:
            template_values['form'] = 'OK'
        return template_values

    template_values['form'] = myform.render()
    return template_values
コード例 #60
-1
 def admin_view(self):
     schema = Schema()
     schema.add(self.context.question_schema_node('dummy', lang = self.get_lang(), context = self.context))
     form = Form(schema)
     self.response['form_resources'] = form.get_widget_resources()
     self.response['dummy_form'] = form.render()
     return self.response