• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pyramid_simpleform.Form类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyramid_simpleform.Form的典型用法代码示例。如果您正苦于以下问题:Python Form类的具体用法?Python Form怎么用?Python Form使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Form类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: login_view

def login_view(request):
    '''Login page'''
    
    referrer = request.session.get('referrer', '')
    if not referrer:
        referrer = request.referrer
        request.session['referrer'] = referrer
        
    
    login_url = request.resource_url(request.root, 'login')
    if referrer == login_url:
        referrer = '/' # never use the login form itself as referrer

    form = Form(request, schema=LoginSchema)
        
    if form.validate():
        user_id = authenticate(form.data['email'], form.data['password'], request.db)
        
        if user_id:
            headers = remember(request, user_id)
            request.session.flash('Login successful.', queue='info')
            del request.session['referrer']
            return HTTPFound(location = referrer, headers = headers)
        else:
            request.session.flash('Invalid email or password.', queue='error')  
    
    return {"renderer":FormRenderer(form)}
开发者ID:circlingthesun,项目名称:Formative,代码行数:27,代码来源:user_accounts.py


示例2: password_edit_view

def password_edit_view(request):
    """ Render the change password form page.

    Seek the database for the user datas based on user_id used in the route. If
    the user did not exist then add an error flash message and redirect to the
    user list.
    If the user exist then render an empty password form. If the form is
    validated then change the user password in the database and add
    success flash message. If the form is not valid, then display again the
    form with validation errors.

    :param request: a ``pyramid.request`` object
    """
    _ = request.translate
    user_id = request.matchdict['user_id']
    user = AuthUser.get_by_id(user_id)
    if not user:
        request.session.flash(_(u"This user did not exist!"), 'error')
        return HTTPFound(location=request.route_path('tools.user_list'))
    form = Form(request, schema=UserPasswordForm, obj=user)
    if 'form_submitted' in request.params and form.validate():
        form.bind(user)
        DBSession.add(user)
        request.session.flash(_(u"Password updated."), 'success')
        return HTTPFound(location=request.route_path('tools.user_list'))
    return dict(renderer=FormRenderer(form))
开发者ID:lazaret,项目名称:anuket,代码行数:26,代码来源:user.py


示例3: api_mentor_assignment_add

def api_mentor_assignment_add(request):
    conn=DBSession()
    validators=dict(fsfileid=formencode.validators.String(not_empty=True,min=16,messages=dict(empty=(u'文件不能为空' ))),\
                    title=formencode.validators.String(not_empty=True,messages=dict(empty=(u'标题不能为空'))),\
                    description=formencode.validators.String(not_empty=True,messages=dict(empty=(u'描述不能为空'))),\
                    duedate=formencode.validators.String(not_empty=True,messages=dict(empty=(u'截止时间不能为空'))),
                    lessonid=formencode.validators.Int(not_empty=True),
                    assignmentid=formencode.validators.Int(not_empty=False))
    form=Form(request,validators=validators,state=State(request=request))
    if form.validate():
        try:
            lesson=conn.query(Lesson).filter(Lesson.id==form.data['lessonid'],Lesson.courseid.in_(\
                                conn.query(Course.id).filter(Course.mentorid.in_(\
                                conn.query(Mentor.id).filter(Mentor.userid==request.user.id))))).first()
            if form.data['assignmentid'] and int(form.data['assignmentid']):
                assignment=conn.query(Assignment).filter(Assignment.id==lesson.assignmentid).first()
                assignment.title=form.data['title']
                assignment.fsfileid=form.data['fsfileid']
                assignment.duedate=time.mktime(time.strptime(form.data['duedate'],'%Y-%m-%d'))
                assignment.description=form.data['description']
                conn.flush()
            else:
                assignment=Assignment()
                assignment.title=form.data['title']
                assignment.fsfileid=form.data['fsfileid']
                assignment.duedate=time.mktime(time.strptime(form.data['duedate'],'%Y-%m-%d'))
                assignment.description=form.data['description']
                conn.add(assignment)
                conn.flush()
                lesson.assignmentid=assignment.id
                conn.flush()
            return dict(return_url='/mentor/lesson/listbycourse?courseid='+str(lesson.courseid))
        except Exception,e:
            log.debug(e)
            return dict(code=301,error=u'参数错误')
开发者ID:frostpeng,项目名称:frostcms,代码行数:35,代码来源:assignment.py


示例4: view_user_edit

    def view_user_edit(self):
        """ View for editing a single user """

        form = Form(self.request, schema=UserEditSchema,
                state=State(request=self.request))

        self.error_message = None
        if form.validate():
            password = self.request.params['password']
            if self.context.validate_password(password):
                if self.request.params['new_password']:
                    password = self.request.params['new_password']
                self.message = 'Successfully saved'
                email = self.request.params['email']
                self.context.edit(password, email)
            else:
                self.error_message = msg['password_invalid']

        _dict = {
            'username': self.context.username,
            'form': FormRenderer(form),
            'email': self.context.email,
            'message': self.message,
            'error_message': self.error_message
        }
        return dict(self.base_dict.items() + _dict.items())
开发者ID:tojuhaka,项目名称:easyblog,代码行数:26,代码来源:views.py


示例5: view_signup

    def view_signup(self):
        """ Register view for new users that aren't signed up yet """
        username = get_param(self.request, 'username')
        email = get_param(self.request, 'email')
        password = u''

        # Create form by using schemas with validations
        form = Form(self.request, schema=SignUpSchema,
                state=State(request=self.request))

        if form.validate():
            username = self.request.params['username']
            password = self.request.params['password']
            email = self.request.params['email']
            get_resource('users', self.request).add(username,
                    password, email)
            get_resource('groups', self.request).add(username,
                    group_names['member'])
            get_resource('groups', self.request).add(username,
                    u'u:%s' % username)
            self.message = msg['succeed_add_user'] + " " + username

        _dict = {
            'url': self.request.application_url + '/signup',
            'username': username,
            'email': email,
            'password': password,
            'form': FormRenderer(form),
            'params': self.request.params,
            'message': self.message
        }
        return dict(self.base_dict.items() + _dict.items())
开发者ID:tojuhaka,项目名称:easyblog,代码行数:32,代码来源:views.py


示例6: login

def login(request):
    message = None
    form = Form(request, schema=UserSchema())
    if request.method == 'POST' and form.validate():
        username = request.params['username']
        password = request.params['password']
        password_again = request.params['password_again']

        if bool(password_again):
            if password == password_again:
                user = form.bind(User())
                DBSession.add(user)
                DBSession.flush()
                user_id = user.id
                headers = remember(request, user.id)
                return HTTPFound(location='/', headers=headers)
            else:
                message = 'Passwords do not match.'
        else:
            user = DBSession.query(User).filter(User.username==username).first()
            if user and user.password == password:
                headers = remember(request, user.id)
                return HTTPFound(location='/', headers=headers)
            else:
                message = 'Username or password is incorrect.'
    return {
        'message': message,
        'form': form,
        'renderer': FormRenderer(form),
        'user': get_user(request),
    }
开发者ID:strazdas,项目名称:task_tracker,代码行数:31,代码来源:views.py


示例7: user_add

def user_add(request):

    form = Form(request, schema=RegistrationSchema)

    if "form.submitted" in request.POST and form.validate():
        session = DBSession()
        username = form.data["username"]
        user = User(username=username, password=form.data["password"], name=form.data["name"], email=form.data["email"])
        session.add(user)

        headers = remember(request, username)

        redirect_url = request.route_url("main")

        return HTTPFound(location=redirect_url, headers=headers)

    login_form = login_form_view(request)

    return {
        "form": FormRenderer(form),
        "toolbar": toolbar_view(request),
        "cloud": cloud_view(request),
        "latest": latest_view(request),
        "login_form": login_form,
    }
开发者ID:urhlednik,项目名称:pylons,代码行数:25,代码来源:views.py


示例8: new

    def new(self):
        user = self.request.user
        form = Form(self.request,
                schema=GallerySchema)
        if form.validate():
            #Generate a name for the new directory. Check if it exists.
            new_directory_name = None
            while not new_directory_name or (DBSession.query(Gallery).filter(Gallery.directory_name == new_directory_name).first()):
                new_directory_name = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(12))
                gallery_directory = self.request.registry.settings['gallery.directory']
                mkdir(path.join(gallery_directory, new_directory_name))
                mkdir(path.join(gallery_directory, new_directory_name, 'raw'))
                mkdir(path.join(gallery_directory, new_directory_name, 'thumbs'))
                mkdir(path.join(gallery_directory, new_directory_name, 'web'))
                data = form.data.copy()
                data['directory_name'] = new_directory_name
                data['created'] = datetime.now()
                data['creator'] = user.id
                #temporary
                del data['permissions']
            gallery = Gallery(**data)
            DBSession.add(gallery)
            DBSession.flush()
            return HTTPFound(self.request.route_url('gallery_view', id=gallery.id))

        return {'request' : self.request,
                'form_rend' : FormRenderer(form)}
开发者ID:adidas,项目名称:pyramid-test,代码行数:27,代码来源:galleries.py


示例9: index

    def index(self):
        tenant = None
        errors = None
        success = None
        tenantForm = None
        contactForm = None
        try:
            tenantService = TenantService()
            tenant = tenantService.GetTenantDetails(self.TenantId)

            tenantForm = Form(self.request, schema=TenantSchema, obj=tenant)
            contactForm = vForm(
                request=self.request, prefix="tenantcontact-", schema=ContactSchema, obj=tenant.Contacts[0]
            )

            valid = tenantForm.validate()
            valid = contactForm.validate() and valid
            if valid:
                tenantForm.bind(tenant)
                contactForm.bind(tenant.Contacts[0])

                tenant.UpdatedBy = self.UserId
                tenant.UpdatedOn = datetime.utcnow()

                if tenantService.SaveTenant(tenant):
                    success = "Company details saved successfully!"
                else:
                    errors = "Error while saving Company details. Please try later."
        except Exception, e:
            log.info(e)
            errors = e.message
开发者ID:cackharot,项目名称:viper-pos,代码行数:31,代码来源:admin.py


示例10: new_topic

def new_topic(request):
    '''
    Create New Topic
    Render form and validate automatically.
    See Schema -> TopicSchema For understand.

    
    '''
    form = Form(request,schema=TopicSchema)
    if form.validate():
        topic = form.data['title']
        author = form.data['author']
        desc = form.data['description']
        date = datetime.datetime.now()
        url = slugfy(topic)
        topic_tuple = {'title' : topic, 
                       'url' : url, 
                       'author': author,
                       'description': desc,
                       'topic_date':date.strftime("%d/%m/%Y"),
                      }
        request.db['topic'].insert(topic_tuple)
        return HTTPFound(location='/')

    return render_to_response('templates/new_topic.html',
                             {'form' : FormRenderer(form),
                              'count':count(request)},
                              request=request)
开发者ID:luizanao,项目名称:pyforum,代码行数:28,代码来源:views.py


示例11: edit

    def edit(self):
        user = self.request.user
        form = Form(self.request,
                schema=GallerySchema)
        gallery = DBSession.query(Gallery).get(self.request.matchdict['id'])
        roles = DBSession.query(Role).all()
        if form.validate():
            gallery.modified = datetime.now()
            gallery.last_update_by = user.id
            gallery.title = form.data['title']
            gallery.description = form.data['description']
            gallery.gallery_date = form.data['gallery_date']
            #Need to make an object exists validator
            temp_perms = []
            for existing_gallery_permission in gallery.permission:
                DBSession.delete(existing_gallery_permission)
            for r_id in form.data['permissions']:
                temp_perms.append(GalleryPermission(gallery_id = gallery.id,
                    role_id = r_id))
            gallery.permission[:] = temp_perms
                
            return HTTPFound(self.request.route_url('gallery_view', id=gallery.id))

        return {'request' : self.request,
                'gallery' : gallery,
                'roles' : roles,
                'form_rend' : FormRenderer(form)}
开发者ID:adidas,项目名称:pyramid-test,代码行数:27,代码来源:galleries.py


示例12: register_view

def register_view(request):
    login = request.POST.get('login')

    form = Form(request,
                    schema = RegisterForm)

    if request.method == 'POST' and form.validate():
        new_user = User(
            username = form.data['login'],
            password = form.data['password'],
            group = 'viewer'
        )
        DBSession.add(new_user)
        user_id = DBSession.query(User).\
                    filter(User.username == new_user.username).first().id
        headers = remember(request, user_id)

        path = os.path.join('./pyramid_app/static/', str(user_id))
        if not os.path.exists(path):
            os.makedirs(path)
        return  HTTPFound('/', headers = headers)
    else:
        return {
            'render' : FormRenderer(form)
        }
开发者ID:pkrysiak,项目名称:pyramid-1.7,代码行数:25,代码来源:views.py


示例13: login

 def login(self):
     if self.logged_in:
         self.request.session.flash('You are already connected!', queue='notice')
         return HTTPFound(
             location=self.request.route_url('home')
         )
     self.c.pagename = 'Login'
     self.c.active_header_nav = 'tools'
     self.c.active_footer_nav = 'tools-login'
     params = self.request.params
     form = Form(self.request, schema=LoginForm, obj=params)
     if form.validate():
         form.bind(params)
         #clear the cache for user
         User.by_username(params.get('username'), invalidate=True)
         user = User.by_username(params.get('username'), cache=None)
         if user:
             password = params.get('password')
             if user.password == User.pass_crypt(password)\
             and user.status == 1:
                 user.last_login_date = sa.func.now()
                 self.request.session.flash(u'Welcome back %s !' % user.username, queue='success')
                 headers = security.remember(self.request,
                                             user.username)
                 return HTTPFound(location=self.request.route_url('home'),
                                  headers=headers)
         self.request.session.flash(u'Wrong username or password!', queue='notice')
     return {
         'item': params,
         'form': FormRenderer(form)
     }
开发者ID:Pylons,项目名称:pylonshq,代码行数:31,代码来源:accounts.py


示例14: forgot_password_view

def forgot_password_view(request):
    '''Forgotten password page'''  
    form = Form(request, schema=ForgotPasswordSchema)
    if form.validate():
        user = request.db.users.find_one({'email':form.data['email']})

        if user:

            new_password = base64.b16encode(os.urandom(4))

            mailer = request.registry['mailer']
            office_email = request.registry.settings['office.email']
            from_ = "%s <%s>" % ("Formative", office_email)
            
            body = """Your password was reset to: %s"""\
                    % new_password

            message = Message(
                      subject='Your new password',
                      sender=office_email,
                      recipients=[form.data['email']],
                      body=body,
                      extra_headers = {"From": from_}
                      )
            
            mailer.send_immediately(message)

            change_password(user['email'], new_password, request.db)

            request.session.flash('Your new password was sent to you.',
                queue='info')
        else:
            request.session.flash('This email address is not recognized.',
                    queue='error')
    return {"renderer":FormRenderer(form)}
开发者ID:circlingthesun,项目名称:Formative,代码行数:35,代码来源:user_accounts.py


示例15: add_message

def add_message(request):
    """
    Add message receive an topic
    """
    form = Form(request,
            schema=MessageSchema
            )
    topic = request.matchdict['name']

    if form.validate():
        title = form.data['title']
        author = form.data['author']
        content = form.data['content']
        topic_oid = topic
        slug = make_slug(title)
        d = {
            'title' : title,
            'author' : author,
            'content':content,
            'topic' : topic_oid,
            'slug' : slug
        }
        request.db['Message'].insert(d)
        return HTTPFound(location='/topic/'+topic)

    return { 'form' : FormRenderer(form), 'topic' : topic }
开发者ID:marioidival,项目名称:pyramid_example_forum,代码行数:26,代码来源:views.py


示例16: linkcheck_add

def linkcheck_add(request):
    form = Form(request, schema=LinkCheckSchema)
    redirect_url = request.route_url('linkchecks')
    if 'form.submitted' in request.POST and form.validate():
        session = DBSession()
        url = form.data['url']
        linkcheck = LinkCheck(
            url=url,
            root_url=form.data['root_url'],
            recursion_level=form.data.get('recursion_level'),
            active=form.data.get('active'),
            check_css=form.data.get('check_css'),
            check_html=form.data.get('check_html'),
            scan_virus=form.data.get('scan_virus'),
            warnings=form.data.get('warnings'),
            warning_size=form.data.get('warning_size'),
            anchors=form.data.get('anchors'),
            cookies=form.data.get('cookies'),
            cookiefile=form.data.get('cookiefile'),
            ignore_url=form.data.get('ignore_url'),
            no_follow_url=form.data.get('no_follow_url'),
            timeout=form.data.get('timeout'),
            pause=form.data.get('pause'),
        )
        session.add(linkcheck)
        return HTTPFound(location=redirect_url)
    elif 'form.canceled' in request.POST:
        return HTTPFound(location=redirect_url)
    return {
        'form': FormRenderer(form),
    }
开发者ID:jean,项目名称:liches,代码行数:31,代码来源:views.py


示例17: view_task

def view_task(request):
    story_id = request.matchdict['story_id']
    story = DBSession.query(Story).get(story_id)
    task_id = request.matchdict['task_id']
    task = DBSession.query(Task).get(task_id)
    times_spent = DBSession.query(TimeSpent.duration).filter(
                                    TimeSpent.task_id==task_id).all()
    form = Form(request, schema=TimeSpentSchema())

    if request.method == 'POST' and form.validate():
        time_spent = form.bind(TimeSpent())
        time_spent.task_id = task_id
        time_spent.task = task
        DBSession.add(time_spent)
        DBSession.flush()
        return HTTPFound(location='/story/%s/task/%s' % (story_id, task_id))
    return {
        'story': story,
        'story_id': story_id,
        'task': task,
        'task_id': task_id,
        'times_spent': times_spent,
        'renderer': FormRenderer(form),
        'form': form,
        'total_time_spent': str(sum_time_spent(times_spent)),
        'user': get_user(request),
    }
开发者ID:strazdas,项目名称:task_tracker,代码行数:27,代码来源:views.py


示例18: signup_post

def signup_post(request):
    dbsession = DBSession()
    settings = request.registry.settings
    form = Form(request, schema=schemas.Signup, obj=User())
    if request.POST and form.validate():
        if not validate_csrf(request):
            return HTTPUnauthorized("Not authorized")
        user = form.bind(User())
        user.username = get_username(user.name, dbsession)
        user.password = func.sha1(user.password)

        cookie = facebook.get_user_from_cookie(
            request.cookies, settings["facebook.app.id"], settings["facebook.app.secret"]
        )
        if cookie:
            graph = facebook.GraphAPI(cookie["access_token"])
            profile = graph.get_object("me")
            user.fb_id = profile["id"]
            user.fb_profile_url = profile["link"]
            user.fb_access_token = cookie["access_token"]

        try:
            dbsession.add(user)
            dbsession.commit()
            headers = remember_me_header(request, user.email)
            redirect_url = route_url("create_profile", request)
            request.response_headerlist = headers
            return {"status": 1, "url": redirect_url}
        except IntegrityError:
            return {"errors": {"form": "Invalid Information"}}

    return {"errors": form.errors}
开发者ID:benzheren,项目名称:carvewith.us,代码行数:32,代码来源:views.py


示例19: contact_view

def contact_view(request):
    form = Form(request, schema=ContactSchema)
        
    if form.validate():
        
        mailer = request.registry['mailer']
        
        office_email = request.registry.settings['office.email']
        
        from_ = "%s <%s>" % (form.data['name'], form.data['email'])
        
        message = Message(
                  subject=form.data['subject'] + ' [formative.co.za]',
                  sender=form.data['email'],
                  recipients=[office_email],
                  body=form.data['message'],
                  extra_headers = {"From": from_}
                  )
        
        mailer.send_immediately(message)
        
        request.session.flash('Message sent.', queue='info')

        return HTTPFound(location="/")
    
    if form.errors:
        request.session.flash('There are errors in your form.', queue='error')
    
    return {"renderer":FormRenderer(form)}
开发者ID:circlingthesun,项目名称:Formative,代码行数:29,代码来源:misc.py


示例20: final_bet

def final_bet(request):
    player = request.authenticated_userid
    final_tip = Final.get_player_tip(player)
    if final_tip:
        request.session.flash(u'You already entered a final tip.')
        return HTTPFound(location=route_url('view_final_tip', request, player=player))

    final_tip = Final(player)

    form = Form(request, schema=FinalBetSchema, obj=final_tip)
    if 'form.submitted' in request.POST and form.validate():
        # verify, that the tip was entered on time
        if FINAL_DEADLINE < datetime.now():
            return HTTPFound(location=route_url('too_late', request))
        final_tip.d_team1 = form.data['d_team1']
        final_tip.d_team2 = form.data['d_team2']
        final_tip.d_score1 = form.data['d_score1']
        final_tip.d_score2 = form.data['d_score2']
        DBSession.add(final_tip)
        return HTTPFound(location=route_url('view_final_tip', request, player=player))

    teams = [(team.d_id,team.d_name) for team in Team.get_all()]

    return { 'tip': final_tip,
             'form': FormRenderer(form),
             'teams': teams,
             'navigation': navigation_view(request) }
开发者ID:mblunier,项目名称:betgame,代码行数:27,代码来源:views.py



注:本文中的pyramid_simpleform.Form类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python renderers.FormRenderer类代码示例发布时间:2022-05-27
下一篇:
Python message.Message类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap