本文整理汇总了Python中pyramid_simpleform.Form类的典型用法代码示例。如果您正苦于以下问题:Python Form类的具体用法?Python Form怎么用?Python Form使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Form类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)}
示例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))
示例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'参数错误')
示例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())
示例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())
示例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),
}
示例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,
}
示例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)}
示例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
示例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)
示例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)}
示例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)
}
示例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)
}
示例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)}
示例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 }