deform表单

守給你的承諾、 提交于 2020-02-07 22:10:11

安装deform

pip install pyramid_deformpip install js.deform

deform表单库介绍

与pyramid同属Pylons Project表单库

Colander:定义表单结构

Peppercom:序列化和反序列化

Chameleon:模板引擎

development.ini里导入pyramid_deform

[app:main]
use = egg:MyShop

pyramid.reload_templates = true
pyramid.debug_authorization = true
pyramid.debug_notfound = false
pyramid.debug_routematch = false
pyramid.default_locale_name = en
pyramid.includes =
    pyramid_debugtoolbar
    pyramid_tm
    pyramid_layout
    pyramid_deform

创建lib/deforms.py文件

# -*- coding:UTF-8 -*-
import colander
import deform
from js.deform import deform as deform_static

class LoginFormSchema(colander.MappingSchema):  # 定义一个LoginFormSchema表单结构 MappingSchema表示一个映射类型
    username = colander.SchemaNode(colander.Str())  # colander.SchemaNode相当于定义的Column
    password = colander.SchemaNode(colander.Str())

在需要的视图views里导入

如login.py中

# -*- coding:UTF-8 -*-
from pyramid.response import Response
from pyramid.view import view_config, view_defaults
from pyramid.httpexceptions import HTTPFound, HTTPBadRequest, HTTPServerError, \
    HTTPForbidden, HTTPUnauthorized
from pyramid.security import remember, forget
from myshop.lib import category, user, deforms
from base import CBase

ctrl = 'login'

# @view_config(route_name='home', renderer='templates/mytemplate.pt')
@view_defaults(route_name='/')
class login(CBase):
    def __init__(self, request):
        CBase.__init__(self, request)
        self.request.title = u'登录'

    @view_config(match_param=('ctrl=%s' % ctrl, 'action=view'),
                 renderer="login.html")
                 # renderer="string")
    def view(self):
        deforms.deform_static.need()  # 使用deform必须步骤
        schema = deforms.LoginFormSchema()  # 声明一个schema
        # 声明一个表单
        form = deforms.deform.Form(schema,
                                   buttons=('submit',))  # 表单上需要哪些按钮
 
        return {
            'title':'login',
            'form':form.render(),  #显示表单
        }

模板login.html中显示声明的表单

<%inherit file="layout/login_base.html"/>
<%block name="log_c">
    <div class="log_c">
        ${form | n}
    </div>
</%block>

显示如下:

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!