def set_properties(self): ckeditor = CKEditor() T = current.T self.fields = [ Field("price", "double", notnull=True, default=0), Field("manufacturer", "string", notnull=True), Field("in_stock", "boolean", notnull=True, default=True), Field("quantity", "integer", default=1), Field("info", "text", notnull=True), Field("option_fields", "list:string"), Field("extra_fields", "list:string"), ] self.validators = { "info": IS_NOT_EMPTY(), "manufacturer": IS_NOT_EMPTY(), } self.widgets = {"info": ckeditor.widget} self.labels = { "price": T("Product Price"), "manufacturer": T("Manufacturer name or brand"), "in_stock": T("Available?"), "info": T("Product specs"), "quantity": T("Quantity in stock"), }
def set_properties(self): ckeditor = CKEditor(self.db) T = current.T self.fields = [ Field("author", "reference auth_user"), Field("title", "string", notnull=True), Field("description", "text"), Field("body_text", "text", notnull=True), Field("slug", "text", notnull=True), ] self.widgets = {"body_text": ckeditor.widget} self.visibility = {"author": (False, False)} self.representation = {"body_text": lambda row, value: XML(value)} self.validators = { "title": IS_NOT_EMPTY(), "body_text": IS_NOT_EMPTY() } self.computations = { "slug": lambda r: IS_SLUG()(r.title)[0], } self.labels = { "title": T("Your post title"), "description": T("Describe your post (markmin allowed)"), "body_text": T("The content") }
def set_properties(self): ckeditor = CKEditor() T = current.T self.fields = [ Field("price", "double", notnull=True, default=0), Field("manufacturer", "string", notnull=True), Field("in_stock", "boolean", notnull=True, default=True), Field("info", "text", notnull=True), Field("product_size", "string"), ] self.validators = { "info": IS_NOT_EMPTY(), "manufacturer": IS_NOT_EMPTY(), "product_size": IS_EMPTY_OR( IS_IN_SET([("L", T("Large")), ("M", T("Medium")), ("S", T("Small"))], zero=None)), } self.widgets = {"info": ckeditor.widget} self.labels = { "price": T("Product Price"), "manufacturer": T("Manufacturer name or brand"), "in_stock": T("Available?"), "info": T("Product specs"), "product_size": T("Product size"), }
def printAnexo2RadioOptions(self, column): """ :rtype : list :param column: uma coluna do banco AVAL_ANEXO_1 :return: A list of form components """ content = [] checkedValue = self.contentForColumn(column) isReadonly = self.columnShouldBeReadonlyForCurrentSession(column) fatores = {"s": "Adequada", "n": "Inadequada"} if not Avaliacao.isCiente(): content.append( INPUT(_name=column, _type='radio', _value='s', requires=IS_NOT_EMPTY(), _disabled=isReadonly, value=checkedValue)) content.append('Adequada') content.append( INPUT(_name=column, _type='radio', _value='n', requires=IS_NOT_EMPTY(), _disabled=isReadonly, value=checkedValue)) content.append('Inadequada') else: content.append(fatores[checkedValue]) return content
def set_properties(self): ckeditor = CKEditor() T = current.T self.fields = [ Field("prep_time", "string", notnull=True), Field("cook_time", "string", notnull=True), Field("difficulty", "string", notnull=True), Field("servings", "double", notnull=True), Field("ingredients", "list:string", notnull=True), Field("instructions", "text", notnull=True), Field("credits", "text"), ] self.validators = { "ingredients": IS_NOT_EMPTY(), "instructions": IS_NOT_EMPTY(), "difficulty": IS_IN_SET([("1", T("Easy")), ("2", T("Medium")), ("3", T("Hard"))], zero=None), "prep_time": IS_NOT_EMPTY(), "cook_time": IS_NOT_EMPTY(), "servings": IS_NOT_EMPTY(), } self.widgets = {"instructions": ckeditor.widget} self.labels = { "instructions": T("Preparation instructions"), "ingredients": T("Ingredients"), "prep_time": T("Preparation time"), "cook_time": T("Cooking time"), "difficulty": T("Difficulty"), "servings": T("Servings"), "credits": T("credits"), } self.comments = { "ingredients": T("One item per line. Press enter to wrap. e.g: 3 cups of water<enter>" ), "instructions": T("You can include pictures."), "prep_time": T("The whole time considering ingredients preparation."), "cook_time": T("The time needed after all ingredients are ready."), "servings": T("How many portions, plates, cups etc?"), "credits": T("Include links, names, books etc."), "difficulty": T("Easy, Medium or hard to cook?"), }
def validatePresetsParams(self, action): if action == 'Create': preset = self.vars.presetCreate else: preset = self.vars.preset if IS_NOT_EMPTY()(preset)[1] is not None: return (False, "Preset name is empty") if IS_ALPHANUMERIC()(preset)[1] is not None: return (False, "Preset name must be alphanumeric") if IS_LENGTH(32)(preset)[1] is not None: return (False, "Preset name must be max 32 chars") if action in ['Create', 'Update']: if IS_NOT_EMPTY()(self.vars.password)[1] is not None: return (False, "Password is empty") if IS_ALPHANUMERIC()(self.vars.password)[1] is not None: return (False, "Password must be alphanumeric") if IS_LENGTH(32)(self.vars.password)[1] is not None: return (False, "Password must be max 32 chars") # check that there's not two buttons for the same action map = {} for button in Controller.__dict__: if isButton(button): value = self.vars[button] if button == "Moonwalk": if value not in [None, 'on', 'off']: return ( False, "Invalid value for Moonwalk: {}".format(value)) else: if value is None: return (False, "Button {} not set".format(button)) else: if value in map: return ( False, "Action {} set for two buttons: {} and {}". format(value, button, map[value])) map[value] = button if self.vars.currenttab not in [ 'Global', 'Techniques1', 'Techniques2', 'Techniques3', 'Techniques4', 'Techniques5', 'Techniques6', 'Techniques7', 'Techniques8', 'Mapping' ]: return (False, "Wrong value for current tab: [{}]".format( self.vars.currenttab)) return (True, None)
def edit(): form = SQLFORM.factory( Field('first_name', 'string', requires=IS_NOT_EMPTY(error_message='Please enter first name')), Field('last_name', 'string', requires=IS_NOT_EMPTY(error_message='Please enter last name')), _action=URL('experiments', 'default', 'edit')) if form.process(session=application.session).accepted: redirect(URL()) return {'form': form}
def set_properties(self): """ """ self.fields = [ Field('first_name', 'string', requires=IS_NOT_EMPTY('Please enter a first name')), Field('last_name', 'string', requires=IS_NOT_EMPTY('Please enter a last name')), Field('email', 'string', requires=IS_EMAIL(error_message='Enter a valid email')) ]
def auth_ini(self, controller, use_username=True, reset_password=False, register=False): self.auth = Auth(self.ui.db, controller=controller, function="login") self.auth.settings.extra_fields[self.auth.settings.table_user_name] = [ Field('agree', 'boolean', default=True, label='I agree to the Terms and Conditions', requires=IS_NOT_EMPTY(error_message='You must agree this!')) ] self.auth.define_tables(username=use_username, migrate=False, fake_migrate=False) self.auth.settings.remember_me_form = False self.auth.settings.reset_password_requires_verification = True if not reset_password: self.auth.settings.actions_disabled.append( 'request_reset_password') if not register: self.auth.settings.actions_disabled.append('register') self.auth.settings.register_next = URL('index', **{'user_signature': True}) self.auth.settings.change_password_next = URL( 'index', **{'user_signature': True}) self.auth.settings.formstyle = 'table3cols' self.auth.settings.allow_basic_login = True self.auth.settings.login_onaccept.append(self.login_onaccept) return self.auth
def set_properties(self): self.fields = [ Field("user_id", "reference auth_user"), Field("writer", "reference auth_user"), Field("board_text", "string"), ] self.visibility = {"user_id": (False, False), "writer": (False, False)} self.validators = {"board_text": IS_NOT_EMPTY()}
def informe_mes_empleado(): empleados = db(db.empleado.is_active is True).select(db.empleado.ALL) fempl = ([" "] + [f"{p.user_code} {p.nombre} {p.apellido}" for p in empleados]) form = FORM( CENTER( H4('Marcadas del personal'), TABLE( TR( TAG('<label class "control-label">Persona</label>'), SELECT(fempl, _name='fempleado', _type='text', _id="persona", _class="form-control string")), TR( TAG('<label class "control-label">Periodo desde</label>'), INPUT(_name='fdesde', _type='date', _id="mesanio", _class="form-control string", requires=IS_NOT_EMPTY())), TR( TAG('<label class "control-label">Periodo hasta</label>'), INPUT( _name='fhasta', _type='date', _id="mesanio", _class="form-control string", ))), BR(), INPUT(_type="submit", _class="btn btn-primary btn-medium", _value='Continuar'))) if form.accepts(request, session): session.empleado = request.vars['fempleado'] session.user_code = request.vars['fempleado'].split()[0] session.fdesde = request.vars['fdesde'] session.fhasta = request.vars['fhasta'] log(f"seleccionado {session.empleado}") log(f"desde: {session.fdesde} hasta {session.fhasta}") # selector = (db.empleado.user_code == user_code) # usuario = db(selector).select().first().as_dict() session.tdesde = datetime.datetime.strptime(session.fdesde, '%Y-%m-%d') session.thasta = datetime.datetime.strptime(session.fhasta, '%Y-%m-%d') lista = aplico_politica(session.user_code, session.fdesde, session.fhasta) nombre_archivo = f'''{session.empleado} -{session.fdesde}-{session.fhasta}''' session.table = list_dict_to_table_sortable(lista, nombre_archivo) redirect(URL('informe')) else: log(f'acceso {request.function}') return dict(form=form)
def set_properties(self): ckeditor = CKEditor() self.fields = [ Field("title", unique=True), Field("description", "text"), Field("page_content", "text"), Field("picture", "upload"), Field("thumbnail", "upload"), Field("tags", "list:string"), Field("slug"), Field("page_scope", "list:string", default=["public", "sitemap"]), Field("visibility"), Field("text_language", default="pt-br"), Field("redirect_url"), ] self.widgets = { "tags": StringListWidget.widget, "page_content": ckeditor.widget } self.comments = { "page_scope": "public, sitemap, members" } self.computations = { "slug": lambda r: IS_SLUG()(r.title)[0], "thumbnail": lambda r: THUMB2(r.picture, 200, 200) } self.validators = { "title": [IS_NOT_EMPTY(), IS_NOT_IN_DB(self.db, "internal_page.title")], "description": IS_NOT_EMPTY(), "picture": IS_EMPTY_OR(IS_IMAGE()), "tags": COMMA_SEPARATED_LIST(), "text_language": IS_IN_SET(["en", "pt-br", "es"]) }
def printCienteInput(self): """ :rtype : gluon.html.DIV """ if self.tipo == 'subordinados': column = 'CIENTE_CHEFIA' elif self.tipo == 'autoavaliacao': column = 'CIENTE_SERVIDOR' if not Avaliacao.isCiente(): # Removi _checked=v por não achar necessário. Caso haja algum problema, reavaliar necessidade return INPUT(_name=column, _value='T', _type='checkbox', requires=IS_NOT_EMPTY()) else: return IMG(_src=URL('static/images', 'checked.png'), _alt='Ciente')
def set_properties(self): ckeditor = CKEditor() T = self.db.T self.fields = [ Field("markup", default="html"), Field("body", "text", notnull=True), ] self.validators = { "body": IS_NOT_EMPTY(), #"markup": IS_IN_SET(["html", "markmin"], zero=None), } self.labels = {"body": T("Article Text")} self.visibility = {"markup": (False, False)} self.widgets = {"body": ckeditor.widget}
def getSpcFile(self): songName = self.vars.songName if IS_NOT_EMPTY()(songName)[1] is not None: raiseHttp(400, "Song is empty") if IS_MATCH('[a-zA-Z0-9_\.() ,\-/]*', strict=True)(songName)[1] is not None: raiseHttp(400, "Invalid char in song name") if IS_LENGTH(64)(songName)[1] is not None: raiseHttp(400, "Song must be max 64 chars") print("getSpcFile songName: {}".format(songName)) musics = self.loadMusics() if songName not in musics: raiseHttp(400, "No preview for this song") if 'spc_path' not in musics[songName] or musics[songName][ 'spc_path'] == "": raiseHttp(400, "No preview for this song") songFile = musics[songName]['spc_path'] with open(os.path.join('music', songFile), 'rb') as spcFile: spcFileData = spcFile.read() return json.dumps({'spc': base64.b64encode(spcFileData).decode()})
def define_tables(self, username=None, signature=None, migrate=None, fake_migrate=None): """ To be called unless tables are defined manually Examples: Use as:: # defines all needed tables and table files # 'myprefix_auth_user.table', ... auth.define_tables(migrate='myprefix_') # defines all needed tables without migration/table files auth.define_tables(migrate=False) """ db = self.db if migrate is None: migrate = db._migrate if fake_migrate is None: fake_migrate = db._fake_migrate settings = self.settings if username is None: username = settings.use_username else: settings.use_username = username if not self.signature: self.define_signature() if signature is True: signature_list = [self.signature] elif not signature: signature_list = [] elif isinstance(signature, Table): signature_list = [signature] else: signature_list = signature self._table_signature_list = signature_list # Should it defined in __init__ first?? is_not_empty = IS_NOT_EMPTY(error_message=self.messages.is_empty) is_crypted = CRYPT(key=settings.hmac_key, min_length=settings.password_min_length) is_unique_email = [ IS_EMAIL(error_message=self.messages.invalid_email), IS_NOT_IN_DB(db, '%s.email' % settings.table_user_name, error_message=self.messages.email_taken) ] if not settings.email_case_sensitive: is_unique_email.insert(1, IS_LOWER()) if settings.table_user_name not in db.tables: passfield = settings.password_field extra_fields = settings.extra_fields.get(settings.table_user_name, []) + signature_list # cas_provider Will always be None here but we compare it anyway so subclasses can use our define_tables if username or settings.cas_provider: is_unique_username = \ [IS_MATCH('[\w\.\-]+', strict=True, error_message=self.messages.invalid_username), IS_NOT_IN_DB(db, '%s.username' % settings.table_user_name, error_message=self.messages.username_taken)] if not settings.username_case_sensitive: is_unique_username.insert(1, IS_LOWER()) db.define_table( settings.table_user_name, Field('first_name', length=128, default='', label=self.messages.label_first_name, requires=is_not_empty), Field('last_name', length=128, default='', label=self.messages.label_last_name, requires=is_not_empty), Field('email', length=512, default='', label=self.messages.label_email, requires=is_unique_email), Field('username', length=128, default='', label=self.messages.label_username, requires=is_unique_username), Field(passfield, 'password', length=512, readable=False, label=self.messages.label_password, requires=[is_crypted]), Field('registration_key', length=512, writable=False, readable=False, default='', label=self.messages.label_registration_key), Field('reset_password_key', length=512, writable=False, readable=False, default='', label=self.messages.label_reset_password_key), Field('registration_id', length=512, writable=False, readable=False, default='', label=self.messages.label_registration_id), *extra_fields, **dict(migrate=self._get_migrate(settings.table_user_name, migrate), fake_migrate=fake_migrate, format='%(username)s')) else: db.define_table( settings.table_user_name, Field('first_name', length=128, default='', label=self.messages.label_first_name, requires=is_not_empty), Field('last_name', length=128, default='', label=self.messages.label_last_name, requires=is_not_empty), Field('email', length=512, default='', label=self.messages.label_email, requires=is_unique_email), Field(passfield, 'password', length=512, readable=False, label=self.messages.label_password, requires=[is_crypted]), Field('registration_key', length=512, writable=False, readable=False, default='', label=self.messages.label_registration_key), Field('reset_password_key', length=512, writable=False, readable=False, default='', label=self.messages.label_reset_password_key), Field('registration_id', length=512, writable=False, readable=False, default='', label=self.messages.label_registration_id), *extra_fields, **dict(migrate=self._get_migrate(settings.table_user_name, migrate), fake_migrate=fake_migrate, format='%(first_name)s %(last_name)s (%(id)s)')) reference_table_user = '******' % settings.table_user_name if settings.table_group_name not in db.tables: extra_fields = settings.extra_fields.get(settings.table_group_name, []) + signature_list db.define_table( settings.table_group_name, Field('role', length=512, default='', label=self.messages.label_role, requires=IS_NOT_IN_DB( db, '%s.role' % settings.table_group_name)), Field('description', 'text', label=self.messages.label_description), *extra_fields, **dict(migrate=self._get_migrate(settings.table_group_name, migrate), fake_migrate=fake_migrate, format='%(role)s (%(id)s)')) reference_table_group = 'reference %s' % settings.table_group_name if settings.table_membership_name not in db.tables: extra_fields = settings.extra_fields.get( settings.table_membership_name, []) + signature_list db.define_table( settings.table_membership_name, Field('user_id', reference_table_user, label=self.messages.label_user_id), Field('group_id', reference_table_group, label=self.messages.label_group_id), *extra_fields, **dict(migrate=self._get_migrate( settings.table_membership_name, migrate), fake_migrate=fake_migrate)) if settings.table_permission_name not in db.tables: extra_fields = settings.extra_fields.get( settings.table_permission_name, []) + signature_list db.define_table( settings.table_permission_name, Field('group_id', reference_table_group, label=self.messages.label_group_id), Field('name', default='default', length=512, label=self.messages.label_name, requires=is_not_empty), Field('table_name', length=512, label=self.messages.label_table_name), Field('record_id', 'integer', default=0, label=self.messages.label_record_id, requires=IS_INT_IN_RANGE(0, 10**9)), *extra_fields, **dict(migrate=self._get_migrate( settings.table_permission_name, migrate), fake_migrate=fake_migrate)) if settings.table_event_name not in db.tables: db.define_table( settings.table_event_name, Field('time_stamp', 'datetime', default=current.request.now, label=self.messages.label_time_stamp), Field('client_ip', default=current.request.client, label=self.messages.label_client_ip), Field('user_id', reference_table_user, default=None, label=self.messages.label_user_id), Field('origin', default='auth', length=512, label=self.messages.label_origin, requires=is_not_empty), Field('description', 'text', default='', label=self.messages.label_description, requires=is_not_empty), *settings.extra_fields.get(settings.table_event_name, []), **dict(migrate=self._get_migrate(settings.table_event_name, migrate), fake_migrate=fake_migrate)) return self
def __call__(self): output = {} T = current.T request = current.request response = current.response s3 = response.s3 # Check logged in and permissions auth = current.auth settings = current.deployment_settings roles = current.session.s3.roles system_roles = auth.get_system_roles() AUTHENTICATED = system_roles.AUTHENTICATED # Login/Registration forms self_registration = current.deployment_settings.get_security_self_registration( ) registered = False login_form = None login_div = None register_form = None register_div = None # Contact Form request_email = settings.get_frontpage("request_email") if request_email: from gluon.dal import Field from gluon.validators import IS_NOT_EMPTY from gluon.sqlhtml import SQLFORM fields = [ Field( "name", label="Your name", requires=IS_NOT_EMPTY(), ), Field( "address", label="Your e-mail address", requires=IS_NOT_EMPTY(), ), Field( "subject", label="Subject", requires=IS_NOT_EMPTY(), ), Field( "message", "text", label="Message", requires=IS_NOT_EMPTY(), ), ] from s3 import s3_mark_required labels, required = s3_mark_required(fields) s3.has_required = required response.form_label_separator = "" contact_form = SQLFORM.factory( formstyle=settings.get_ui_formstyle(), submit_button=T("Submit"), labels=labels, separator="", table_name="contact", # Dummy table name _id="mailform", *fields) if contact_form.accepts(request.post_vars, current.session, formname="contact_form", keepvalues=False, hideerror=False): # Processs Contact Form form_vars = contact_form.vars sender = "%s <%s>" % (form_vars.name, form_vars.address) result = current.msg.send_email( to=request_email, sender=sender, subject=form_vars.subject, message=form_vars.message, reply_to=form_vars.address, ) if result: response.confirmation = "Thank you for your message - we'll be in touch shortly" if s3.cdn: if s3.debug: s3.scripts.append( "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js" ) else: s3.scripts.append( "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js" ) else: if s3.debug: s3.scripts.append("/%s/static/scripts/jquery.validate.js" % request.application) else: s3.scripts.append( "/%s/static/scripts/jquery.validate.min.js" % request.application) validation_script = ''' $('#mailform').validate({ errorClass:'req', rules:{ name:{ required:true }, address: { required:true, email:true }, subject:{ required:true }, message:{ required:true } }, messages:{ name:"Enter your name", subject:"Enter a subject", message:"Enter a message", address:{ required:"Please enter a valid email address", email:"Please enter a valid email address" } }, errorPlacement:function(error,element){ error.appendTo(element.parents('div.controls')) }, submitHandler:function(form){ form.submit() } })''' s3.jquery_ready.append(validation_script) else: contact_form = "" if AUTHENTICATED not in roles: login_buttons = DIV(A(T("Login"), _id="show-login", _class="tiny secondary button"), _id="login-buttons") script = ''' $('#show-mailform').click(function(e){ e.preventDefault() $('#intro').slideDown(400, function() { $('#login_box').hide() }); }) $('#show-login').click(function(e){ e.preventDefault() $('#login_form').show() $('#register_form').hide() $('#login_box').show() $('#intro').slideUp() })''' s3.jquery_ready.append(script) # This user isn't yet logged-in if request.cookies.has_key("registered"): # This browser has logged-in before registered = True if self_registration is True: # Provide a Registration box on front page login_buttons.append( A(T("Register"), _id="show-register", _class="tiny secondary button", _style="margin-left:5px")) script = ''' $('#show-register').click(function(e){ e.preventDefault() $('#login_form').hide() $('#register_form').show() $('#login_box').show() $('#intro').slideUp() })''' s3.jquery_ready.append(script) register_form = auth.register() register_div = DIV(H3(T("Register")), P(XML(T("If you would like to help, then please %(sign_up_now)s") % \ dict(sign_up_now=B(T("sign-up now")))))) register_script = ''' $('#register-btn').click(function(e){ e.preventDefault() $('#register_form').show() $('#login_form').hide() }) $('#login-btn').click(function(e){ e.preventDefault() $('#register_form').hide() $('#login_form').show() })''' s3.jquery_ready.append(register_script) # Provide a login box on front page auth.messages.submit_button = T("Login") login_form = auth.login(inline=True) login_div = DIV(H3(T("Login")), P(XML(T("Registered users can %(login)s to access the system") % \ dict(login=B(T("login")))))) else: login_buttons = "" output["login_buttons"] = login_buttons output["self_registration"] = self_registration output["registered"] = registered output["login_div"] = login_div output["login_form"] = login_form output["register_div"] = register_div output["register_form"] = register_form output["contact_form"] = contact_form # Slick slider if s3.debug: s3.scripts.append("/%s/static/scripts/slick.js" % request.application) else: s3.scripts.append("/%s/static/scripts/slick.min.js" % request.application) script = ''' $(document).ready(function(){ $('#title-image').slick({ autoplay:true, autoplaySpeed:5000, speed:1000, fade:true, cssEase:'linear' }); });''' s3.jquery_ready.append(script) self._view(TEMPLATE, "index.html") return output
def __call__(self): output = {} T = current.T request = current.request response = current.response s3 = response.s3 # Check logged in and permissions auth = current.auth settings = current.deployment_settings roles = current.session.s3.roles system_roles = auth.get_system_roles() AUTHENTICATED = system_roles.AUTHENTICATED # Login/Registration forms self_registration = settings.get_security_registration_visible() registered = False login_form = None login_div = None register_form = None register_div = None # Project Links project_links = DIV(_class="title-links hide-for-small") project_description = settings.get_frontpage("project_description") if project_description: project_links.append( A( ICON("link"), T("Project Description"), _class="action-lnk", _href=project_description, _target="_blank", )) project_links.append( A( ICON("link"), T("User Manual"), _class="action-lnk", _href=URL( c="default", f="index", args=["docs"], vars={"name": "UserManual"}, ), _target="_blank", )) mailing_list = settings.get_frontpage("mailing_list") if mailing_list: project_links.append( A( ICON("link"), T("Mailing List"), _class="action-lnk", _href=mailing_list, _target="_blank", )) # Contact Form request_email = settings.get_frontpage("request_email") if request_email: from s3dal import Field from gluon.validators import IS_NOT_EMPTY from gluon.sqlhtml import SQLFORM fields = [ Field( "name", label="Your name", requires=IS_NOT_EMPTY(), ), Field( "address", label="Your e-mail address", requires=IS_NOT_EMPTY(), ), Field( "subject", label="Subject", requires=IS_NOT_EMPTY(), ), Field( "message", "text", label="Message", requires=IS_NOT_EMPTY(), ), ] from s3 import s3_mark_required labels, required = s3_mark_required(fields) s3.has_required = required response.form_label_separator = "" contact_form = SQLFORM.factory( formstyle=settings.get_ui_formstyle(), submit_button=T("Submit"), labels=labels, separator="", table_name="contact", # Dummy table name _id="mailform", *fields) if contact_form.accepts(request.post_vars, current.session, formname="contact_form", keepvalues=False, hideerror=False): # Processs Contact Form form_vars = contact_form.vars sender = "%s <%s>" % (form_vars.name, form_vars.address) result = current.msg.send_email( to=request_email, sender=sender, subject=form_vars.subject, message=form_vars.message, reply_to=form_vars.address, ) if result: response.confirmation = "Thank you for your message - we'll be in touch shortly" if s3.cdn: if s3.debug: s3.scripts.append( "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js" ) else: s3.scripts.append( "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js" ) else: if s3.debug: s3.scripts.append("/%s/static/scripts/jquery.validate.js" % request.application) else: s3.scripts.append( "/%s/static/scripts/jquery.validate.min.js" % request.application) validation_script = ''' $('#mailform').validate({ errorClass:'req', rules:{ name:{ required:true }, address: { required:true, email:true }, subject:{ required:true }, message:{ required:true } }, messages:{ name:"Enter your name", subject:"Enter a subject", message:"Enter a message", address:{ required:"Please enter a valid email address", email:"Please enter a valid email address" } }, errorPlacement:function(error,element){ error.appendTo(element.parents('div.controls')) }, submitHandler:function(form){ form.submit() } })''' s3.jquery_ready.append(validation_script) else: contact_form = "" if AUTHENTICATED not in roles: login_buttons = DIV(A(T("Login"), _id="show-login", _class="tiny secondary button"), _id="login-buttons") script = ''' $('#show-mailform').click(function(e){ e.preventDefault() $('#login_box').fadeOut(function(){$('#intro').fadeIn()}) }) $('#show-login').click(function(e){ e.preventDefault() $('#login_form').show() $('#register_form').hide() $('#intro').fadeOut(function(){$('#login_box').fadeIn()}) })''' s3.jquery_ready.append(script) # This user isn't yet logged-in if request.cookies.has_key("registered"): # This browser has logged-in before registered = True if self_registration is True: # Provide a Registration box on front page login_buttons.append( A(T("Register"), _id="show-register", _class="tiny secondary button", _style="margin-left:5px")) script = ''' $('#show-register').click(function(e){ e.preventDefault() $('#login_form').hide() $('#register_form').show() $('#intro').fadeOut(function(){$('#login_box').fadeIn()}) })''' s3.jquery_ready.append(script) register_form = auth.register() register_div = DIV(H3(T("Register")), P(XML(T("If you would like to help, then please %(sign_up_now)s") % \ dict(sign_up_now=B(T("sign-up now")))))) register_script = ''' $('#register-btn').click(function(e){ e.preventDefault() $('#login_form').fadeOut(function(){$('#register_form').fadeIn()}) }) $('#login-btn').click(function(e){ e.preventDefault() $('#register_form').fadeOut(function(){$('#login_form').fadeIn()}) })''' s3.jquery_ready.append(register_script) # Provide a login box on front page auth.messages.submit_button = T("Login") login_form = auth.login(inline=True) login_div = DIV(H3(T("Login")), P(XML(T("Registered users can %(login)s to access the system") % \ dict(login=B(T("login")))))) else: login_buttons = "" # Create output dict output = { "login_buttons": login_buttons, "self_registration": self_registration, "registered": registered, "login_div": login_div, "login_form": login_form, "register_div": register_div, "register_form": register_form, "contact_form": contact_form, "project_links": project_links, } # Count records (@todo: provide total/updated counters?) s3db = current.s3db db = current.db # Organisations table = s3db.org_organisation query = (table.deleted != True) count = table.id.count() row = db(query).select(count).first() output["total_organisations"] = row[count] # Service Locations (@todo) #table = s3db.org_service_location #query = (table.deleted != True) #count = table.id.count() #row = db(query).select(count).first() output["total_services"] = 0 #row[count] # Needs lists table = s3db.req_organisation_needs query = (table.deleted != True) count = table.id.count() row = db(query).select(count).first() output["total_needs"] = row[count] # Frontpage Feed Control if settings.frontpage.rss: s3.external_stylesheets.append( "http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.css" ) s3.scripts.append( "http://www.google.com/jsapi?key=notsupplied-wizard") s3.scripts.append( "http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.js" ) counter = 0 feeds = "" for feed in settings.frontpage.rss: counter += 1 feeds = "".join((feeds, "{title:'%s',\n" % feed["title"], "url:'%s'}" % feed["url"])) # Don't add a trailing comma for old IEs if counter != len(settings.frontpage.rss): feeds += ",\n" # feedCycleTime: milliseconds before feed is reloaded (5 minutes) feed_control = "".join((''' function LoadDynamicFeedControl(){ var feeds=[ ''', feeds, ''' ] var options={ feedCycleTime:300000, numResults:5, stacked:true, horizontal:false, title:"''', str(T("News")), '''" } new GFdynamicFeedControl(feeds,'feed-control',options) } google.load('feeds','1') google.setOnLoadCallback(LoadDynamicFeedControl)''')) s3.js_global.append(feed_control) s3.stylesheets.append("../themes/RW/homepage.css") self._view(TEMPLATE, "index.html") return output
def customise_pr_person_resource(r, tablename): T = current.T s3db = current.s3db table = r.resource.table # Disallow "unknown" gender and defaults to "male" evr_gender_opts = dict( (k, v) for k, v in s3db.pr_gender_opts.items() if k in (2, 3)) gender = table.gender gender.requires = IS_IN_SET(evr_gender_opts, zero=None) gender.default = 3 if r.controller == "evr": # Hide evacuees emergency contacts current.deployment_settings.pr.show_emergency_contacts = False # Last name and date of birth mandatory in EVR module table.last_name.requires = IS_NOT_EMPTY( error_message=T("Please enter a last name")) dob_requires = s3_date("dob", future=0, past=1320, empty=False).requires dob_requires.error_message = T("Please enter a date of birth") table.date_of_birth.requires = dob_requires # Enable Location_id from gluon import DIV from s3 import S3LocationSelector location_id = table.location_id location_id.readable = location_id.writable = True location_id.label = T("Place of Birth") levels = ( "L1", "L2", "L3", ) location_id.widget = S3LocationSelector( levels=levels, lines=True, ) location_id.represent = s3db.gis_LocationRepresent(sep=" | ") # Enable place of birth place_of_birth = s3db.pr_person_details.place_of_birth place_of_birth.label = "Specify a Different Place of Birth" place_of_birth.comment = DIV( _class="tooltip", _title="%s|%s" % (T("Different Place of Birth"), T("Specify a different place of birth (foreign country, village, hamlet)" ))) place_of_birth.readable = place_of_birth.writable = True # Disable religion selection s3db.pr_person_details.religion.readable = False s3db.pr_person_details.religion.writable = False # Disable unneeded physical details pdtable = s3db.pr_physical_description hide_fields = [ "race", "complexion", "height", "weight", "hair_length", "hair_style", "hair_baldness", "hair_comment", "facial_hair_type", "facial_hair_length", "facial_hair_color", "facial_hair_comment", "body_hair", "skin_marks", "medical_conditions" ] for fname in hide_fields: field = pdtable[fname] field.readable = field.writable = False # This set is suitable for Italy ethnicity_opts = ( "Italian", "Chinese", "Albanese", "Philippine", "Pakistani", "English", "African", "Other", "Unknown", ) ethnicity_opts = dict((v, T(v)) for v in ethnicity_opts) ethnicity = pdtable.ethnicity ethnicity.requires = IS_EMPTY_OR(IS_IN_SET(ethnicity_opts, sort=True)) ethnicity.represent = S3Represent(options=ethnicity_opts, translate=True)
"Enabled admin login ip pattern. Comma-separated list (recommended to set the firewall)", value="") db.settings.insert( fieldname="request_enabled_lst", description= "Enabled request ip pattern. Comma-separated list (recommended to set the firewall)", value="") from gluon.tools import Auth auth = Auth(db) auth.settings.extra_fields['auth_user'] = [ Field('agree', 'boolean', default=True, label=T('I agree to the terms and conditions'), requires=IS_NOT_EMPTY(error_message='You must agree this!')) ] auth.define_tables(username=True, migrate=False, fake_migrate=False) createTable(db[auth.settings.table_user_name]) createTable(db[auth.settings.table_group_name]) createTable(db[auth.settings.table_membership_name]) createTable(db[auth.settings.table_event_name]) createTable(db[auth.settings.table_cas_name]) #temp. test users! db.auth_user.insert( username="******", #password: 12345 email="*****@*****.**", password= "******" ) db.auth_user.insert(
from gluon.storage import Storage # create DAL connection (and create DB if not exists) db = DAL('sqlite://guitest.sqlite', folder=None) # define a table 'person' (create/aster as necessary) person = db.define_table( 'person', Field('name', 'string', length=100), Field('sex', 'string', length=1), Field('active', 'boolean', comment="check!"), Field('bio', 'text', comment="resume (CV)"), ) # set sample validator (do not allow empty nor duplicate names) db.person.name.requires = [IS_NOT_EMPTY(), IS_NOT_IN_DB(db, 'person.name')] db.person.sex.requires = IS_IN_SET({'M': 'Male', 'F': 'Female'}) # create the wxPython GUI application instance: app = wx.App(False) # create a testing frame (wx "window"): f = wx.Frame(None, title="web2py/gui2py sample app") # create the web2py FORM based on person table form = SQLFORM(db.person) # create the HTML "browser" window: html = wx.html.HtmlWindow(f, style=wx.html.HW_DEFAULT_STYLE | wx.TAB_TRAVERSAL) # convert the web2py FORM to XML and display it
def __new__(cls, **kwargs): instance = super(PERSON_FORM, cls).__new__(cls) instance.person = kwargs.get('person') # PERSON type instance.readonly = kwargs.get('readonly') or False instance.readonly_fields = kwargs.get('readonly_fields') or [] my_logger.debug(message='instance.person:%s' % instance.person) my_logger.debug(message='instance.person.creator:%s' % instance.person.creator) if instance.person is not None: current.db.person.first_name.default = instance.person.first_name if 'first_name' in instance.readonly_fields: current.db.person.first_name.writable = False current.db.person.last_name.default = instance.person.last_name if 'last_name' in instance.readonly_fields: current.db.person.last_name.writable = False current.db.person.email.default = instance.person.email if 'email' in instance.readonly_fields: current.db.person.email.writable = False current.db.person.contact.default = instance.person.contact if 'contact' in instance.readonly_fields: current.db.person.contact.writable = False current.db.person.email.requires = [ IS_NOT_EMPTY(), IS_EMAIL(), IS_NOT_IN_DB( current.db(current.db.person.id != instance.person.id), current.db.person.email) ] # creator is a computed field and then not shown by web2py # we need to add it manually instance.form = SQLFORM.factory(Field('creator', 'string', writable=not 'creator' in instance.readonly_fields, label=cc.get_string("PERSON_CREATOR_LABEL"), default=instance.person.creator.email \ if instance.person.creator is not None \ else ''), # creator should exists - backward compatibility current.db.person, Field('is_all_entity', 'boolean', label=cc.get_string("PERSON_IS_ALL_ENTITY_LABEL"), comment=cc.get_string("PERSON_IS_ALL_ENTITY_COMMENT"), represent=lambda r: current.T(str(instance.person.is_all_entity())), # disabled if the user is not admin readable=current.auth.has_membership('all_entity') or \ current.auth.has_membership('admin_entity') or \ current.auth.has_permission('admin'), # admin_ENTITY: backward compatibility writable=(current.auth.has_membership('all_entity') or \ current.auth.has_membership('admin_entity') or \ current.auth.has_permission('admin')) and \ not 'custom_entity' in instance.readonly_fields, # for an update request, pre populating the widget if the user is in all entities default=instance.person.is_all_entity(), ), Field('custom_entity', 'list:reference entity', comment=cc.get_string("PERSON_ENTITY_COMMENT"), label=cc.get_string("PERSON_ENTITY_LABEL"), required=True, notnull=True, writable=not 'custom_entity' in instance.readonly_fields, # for an update request, pre populating the widget given the user entities default=[_entity.id for _entity in instance.person.entities] \ if instance.person.entities is not None \ else [], requires=[IS_IN_DB_AND_USER_ENTITY(current.db(current.db.entity.id > 0), current.db.entity.id, current.db.entity._format, multiple=True), IS_ONE_SELECTED(db=current.db, table=current.db.entity, table_set=~current.db.entity.role.like('user_%'))], represent=lambda r: XML(' <br/>'.join(['%s' % (e.name) \ for e in instance.person.entities])) \ if (not instance.person.is_all_entity() and instance.person.entities is not None) else 'X', widget=lambda field, value: SQLFORM.widgets.multiple.widget(field, value, _class='required')), Field('is_admin', 'boolean', label=cc.get_string("PERSON_IS_ADMIN_LABEL"), comment=cc.get_string("PERSON_IS_ADMIN_COMMENT"), represent=lambda r: current.T(str(instance.person.is_admin())), # disabled if the user is not admin readable=current.auth.has_permission('admin'), writable=current.auth.has_permission('admin') and not 'is_admin' in instance.readonly_fields, # for an update request, pre populating the widget if the user is admin default=instance.person.is_admin(), ), Field('custom_permission', 'string', # this does not matter given that we define our own permission widget label=cc.get_string("PERSON_ENTITY_PERMISSION_LABEL"), required=True, notnull=True, writable=not 'custom_permission' in instance.readonly_fields, # for an update request, pre populating the widget given the user permissions default=[_permission.name for _permission in instance.person.permissions], comment=cc.get_string("PERSON_ENTITY_PERMISSION_COMMENT"), requires=IS_CHIMITHEQUE_PERMISSION(), represent=lambda r: PermissionWidget.represent(r), widget=lambda field, value: PermissionWidget.widget(field, value, _class='required', auth_user_permissions=[_permission.name for _permission in PERSON_MAPPER().find_permissions(current.auth.user.id)] \ if not current.auth.has_permission('admin') \ else None)), readonly=instance.readonly, comments=not instance.readonly, next=URL(current.request.application, 'user', 'list'), submit_button=cc.get_string("SUBMIT") ) else: instance.form = SQLFORM.factory( Field('None', 'string', writable=False, readable=False)) return instance
def customise_pr_person_resource(r, tablename): s3db = current.s3db table = r.resource.table # Disallow "unknown" gender and defaults to "male" evr_gender_opts = dict( (k, v) for k, v in s3db.pr_gender_opts.items() if k in (2, 3)) gender = table.gender gender.requires = IS_IN_SET(evr_gender_opts, zero=None) gender.default = 3 if r.controller == "evr": # Hide evacuees emergency contacts settings.pr.show_emergency_contacts = False # Last name and date of birth mandatory in EVR module table.last_name.requires = IS_NOT_EMPTY( error_message=T("Please enter a last name")) dob_requires = s3_date("dob", future=0, past=1320, empty=False).requires dob_requires.error_message = T("Please enter a date of birth") table.date_of_birth.requires = dob_requires s3db.pr_person_details.place_of_birth.requires = IS_NOT_EMPTY( error_message=T("Please enter a place of birth")) # Disable unneeded physical details pdtable = s3db.pr_physical_description hide_fields = [ "race", "complexion", "height", "weight", "hair_length", "hair_style", "hair_baldness", "hair_comment", "facial_hair_type", "facial_hair_length", "facial_hair_color", "facial_hair_comment", "body_hair", "skin_marks", "medical_conditions" ] for fname in hide_fields: field = pdtable[fname] field.readable = field.writable = False # This set is suitable for Italy ethnicity_opts = ( "Italian", "Chinese", "Albanese", "Philippine", "Pakistani", "English", "African", "Other", "Unknown", ) ethnicity_opts = dict((v, T(v)) for v in ethnicity_opts) ethnicity = pdtable.ethnicity ethnicity.requires = IS_EMPTY_OR(IS_IN_SET(ethnicity_opts, sort=True)) ethnicity.represent = S3Represent(options=ethnicity_opts, translate=True) # Enable place of birth place_of_birth = s3db.pr_person_details.place_of_birth place_of_birth.readable = place_of_birth.writable = True
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys sys.path.append( '/Users/xcbfreedom/projects/web2py/web2py.app/Contents/Resources/') from gluon.dal import DAL, Field from gluon.sqlhtml import SQLFORM from gluon.validators import IS_NOT_EMPTY, IS_EMAIL, IS_LENGTH db = DAL("sqlite://data/mydb.sqlite") db.define_table('t_contact', Field("name"), Field("email"), Field("phone")) db.t_contact.name.requires = IS_NOT_EMPTY() db.t_contact.email.requires = IS_EMAIL() db.t_contact.phone.requires = IS_LENGTH(14) #====insert print db.t_contact.insert(**dict(name="fx", email="x.comll", phone='123')) print db.t_contact.insert(**dict(name="axbc", email="x.comll", phone='123')) db.commit() print 'insert ok' #====select print "select " print db(db.t_contact.phone == '123').select() print "select one" print db.t_contact(**dict(phone='123'))
def set_properties(self): ckeditor = CKEditor() T = current.T self.fields = [ Field("prep_time", "string", notnull=True), Field("cook_time", "string", notnull=True), Field("difficulty", "string", notnull=True), Field("servings", "double", notnull=True), Field("ingredients", "list:string", notnull=True), Field("instructions", "text", notnull=True), Field("credits", "text"), Field("video_source", "string"), Field("video_embed", "string"), Field("active_tab", "string", default="photo"), ] self.validators = { "ingredients": IS_NOT_EMPTY(), "instructions": IS_NOT_EMPTY(), "difficulty": IS_IN_SET([("1", T("Easy")), ("2", T("Medium")), ("3", T("Hard"))], zero=None), "prep_time": IS_NOT_EMPTY(), "cook_time": IS_NOT_EMPTY(), "servings": IS_NOT_EMPTY(), } self.widgets = { "instructions": ckeditor.widget, "ingredients": ListWidget.widget } self.labels = { "instructions": T("Preparation instructions"), "ingredients": T("Ingredients"), "prep_time": T("Preparation time"), "cook_time": T("Cooking time"), "difficulty": T("Difficulty"), "servings": T("Servings"), "credits": T("credits"), "video_source": T("Video source"), "video_embed": T("Video link or code"), "active_tab": T("By default show video or picture"), } self.comments = { "ingredients": T("Include one item then press enter or click in 'add new' to include more" ), "instructions": T("Describe the steps to cook the recipe, also you can include aditional photos and links." ), "prep_time": T("The whole time considering ingredients preparation."), "cook_time": T("The time needed after all ingredients are ready."), "servings": T("This recipe serves how many people?"), "credits": T("Include links, names, books etc."), "difficulty": T("Easy, Medium or hard to cook?"), "video_source": T("Is your video hosted at youtube or vimeo? Leave blank if you have no video." ), "video_embed": T("Please input only the code or link to the video i.e: http://vimeo.com/454545 or only 454545" ), "active_tab": T("Choose what to show or leave photo as default"), }
from gluon.validators import IS_NOT_EMPTY, IS_EXPR from gluon.storage import Storage from gluon import current # web2py SQLFORM expects T in current (thread-local data) to translate messages current.T = lambda x: x if __name__ == '__main__': app = wx.App(False) w = gui.HtmlWindow(None, title="test html", visible=False, resizable=True) if '--login' in sys.argv: form = FORM( LABEL("Username", _width="25%"), INPUT(_type='text', _name='username', requires=IS_NOT_EMPTY(), _width="75%"), LABEL("Password", _width="25%"), INPUT(_type='password', _name='password', requires=IS_NOT_EMPTY(), _width="75%"), LABEL("Options:", _width="25%"), INPUT(_type='checkbox', _name='rememberme', _width="10%"), LABEL("Remember me", _width="65%"), LABEL("", _width="25%"), INPUT(_type='checkbox', _name='superuser', _width="10%"), LABEL("Log in as root", _width="65%"), CENTER( INPUT(_type='submit', _name='login', _value="Login"), BR(), A("lost password", _href="saraza"), " | ", A("register", _href="saraza"),
def login(self, log=DEFAULT, **kwargs): """ Login a user Keyword Args: username/email/name_of_your_username_field (string) - username password/name_of_your_passfield (string) - user's password remember_me (boolean) - extend the duration of the login to settings.long_expiration """ settings = self.settings session = current.session table_user = self.table_user() if 'username' in table_user.fields or \ not settings.login_email_validate: userfield_validator = IS_NOT_EMPTY( error_message=self.messages.is_empty) if not settings.username_case_sensitive: userfield_validator = [IS_LOWER(), userfield_validator] else: userfield_validator = IS_EMAIL( error_message=self.messages.invalid_email) if not settings.email_case_sensitive: userfield_validator = [IS_LOWER(), userfield_validator] passfield = settings.password_field if log is DEFAULT: log = self.messages['login_log'] user = None # Setup the default field used for the userfield if self.settings.login_userfield: userfield = self.settings.login_userfield else: if 'username' in table_user.fields: userfield = 'username' else: userfield = 'email' # Get the userfield from kwargs and validate it userfield_value = kwargs.get(userfield) if userfield_value is None: raise KeyError('%s not found in kwargs' % userfield) validated, error = self.__validate(userfield_value, userfield_validator) if error: return { 'errors': { userfield: error }, 'message': self.messages.invalid_login, 'user': None } # Get the user for this userfield and check it user = table_user(**{userfield: validated}) if user is None: return { 'errors': { userfield: self.messages.invalid_user }, 'message': self.messages.invalid_login, 'user': None } if (user.registration_key or '').startswith('pending'): return { 'errors': None, 'message': self.messages.registration_pending, 'user': None } elif user.registration_key in ('disabled', 'blocked'): return { 'errors': None, 'message': self.messages.login_disabled, 'user': None } elif (user.registration_key is not None and user.registration_key.strip()): return { 'errors': None, 'message': self.messages.registration_verifying, 'user': None } # Finally verify the password passfield = settings.password_field password = table_user[passfield].validate(kwargs.get(passfield, ''))[0] if password == user[passfield]: self.login_user(user) session.auth.expiration = \ kwargs.get('remember_me', False) and \ settings.long_expiration or \ settings.expiration session.auth.remember_me = kwargs.get('remember_me', False) self.log_event(log, user) return { 'errors': None, 'message': self.messages.logged_in, 'user': { k: user[k] for k in table_user.fields if table_user[k].readable } } else: self.log_event(self.messages['login_failed_log'], kwargs) return { 'errors': { passfield: self.messages.invalid_password }, 'message': self.messages.invalid_login, 'user': None }
def select(): import re db = get_database(request) dbname = request.args[0] regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)') if len(request.args) > 1 and hasattr(db[request.args[1]], '_primarykey'): regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)') if request.vars.query: match = regex.match(request.vars.query) if match: request.vars.query = '%s.%s.%s==%s' % ( request.args[0], match.group('table'), match.group('field'), match.group('value')) else: request.vars.query = session.last_query query = get_query(request) if request.vars.start: start = int(request.vars.start) else: start = 0 nrows = 0 stop = start + 100 table = None rows = [] orderby = request.vars.orderby if orderby: orderby = dbname + '.' + orderby if orderby == session.last_orderby: if orderby[0] == '~': orderby = orderby[1:] else: orderby = '~' + orderby session.last_orderby = orderby session.last_query = request.vars.query form = FORM(TABLE( TR( T('Query:'), '', INPUT(_style='width:400px', _name='query', _value=request.vars.query or '', requires=IS_NOT_EMPTY(error_message=T("Cannot be empty")))), TR( T('Update:'), INPUT(_name='update_check', _type='checkbox', value=False), INPUT(_style='width:400px', _name='update_fields', _value=request.vars.update_fields or '')), TR( T('Delete:'), INPUT(_name='delete_check', _class='delete', _type='checkbox', value=False), ''), TR('', '', INPUT(_type='submit', _value='submit'))), _action=URL(r=request, args=request.args)) if request.vars.csvfile != None: try: import_csv(db[request.vars.table], request.vars.csvfile.file) response.flash = T('data uploaded') except Exception, e: response.flash = DIV(T('unable to parse csv file'), PRE(str(e)))
def _login_form(self, openid_field_label=None, submit_button=None, _next=None, style=None): """ Render the form for OpenID login """ def warning_openid_fail(session): session.warning = messages.openid_fail_discover style = style or """ background-attachment: scroll; background-repeat: no-repeat; background-image: url("http://wiki.openid.net/f/openid-16x16.gif"); background-position: 0% 50%; background-color: transparent; padding-left: 18px; width: 400px; """ style = style.replace("\n", "") request = self.environment.request session = self.environment.session messages = self.messages hidden_next_input = "" if _next == 'profile': profile_url = self.environment.URL(r=request, f='user', args=['profile']) hidden_next_input = INPUT(_type="hidden", _name="_next", _value=profile_url) form = FORM(openid_field_label or self.messages.label_alt_login_username, INPUT(_type="input", _name="oid", requires=IS_NOT_EMPTY( error_message=messages.openid_fail_discover), _style=style), hidden_next_input, INPUT(_type="submit", _value=submit_button or messages.submit_button), " ", A(messages.comment_openid_signin, _href=messages.comment_openid_help_url, _title=messages.comment_openid_help_title, _class='openid-identifier', _target="_blank"), _action=self.login_url) if form.accepts(request.vars, session): oid = request.vars.oid consumerhelper = self._init_consumerhelper() url = self.login_url return_to_url = self.return_to_url if not oid: warning_openid_fail(session) redirect(url) try: if request.vars.has_key('_next'): return_to_url = self.return_to_url + '?_next=' + request.vars._next url = consumerhelper.begin(oid, self.realm, return_to_url) except DiscoveryFailure: warning_openid_fail(session) redirect(url) return form
def restore_backup(): response.subtitle = T("Restore the Customer Data") response.view = 'nas/index.html' msg_result = T('Starting the process?') if request.post_vars: if request.post_vars.alias == None or request.post_vars.alias == "": msg_result = T("Error: Missing alias parameter!") if request.post_vars.has_key("frm_file"): if request.post_vars.bfile == "": msg_result = T("Error: Missing upload file!") else: msg_result = dbtool.loadBackupData( alias=request.vars.alias, bfile=request.post_vars.bfile) else: if request.post_vars.filename == "": msg_result = T("Error: Missing upload filename!") else: msg_result = dbtool.loadBackupData( alias=request.vars.alias, filename=request.post_vars.filename) request.post_vars = None alias = db( (db.databases.deleted == False)).select(db.databases.id, db.databases.alias, orderby=db.databases.alias) cmb_alias = SELECT( *[OPTION(field["alias"], _value=field["alias"]) for field in alias], _name="alias", _id="cmb_alias") if len(cmb_alias) == 0: cmb_alias.insert(0, OPTION("", _value="")) dfiles = os.listdir(os.path.join(ns.request.folder, 'static/backup')) files = [] for dfile in dfiles: if str(dfile).endswith(".backup") or str(dfile).endswith(".xml"): files.append(dfile) files.sort() cmb_files = SELECT(*files, _id="cmb_files", _name="filename") if len(cmb_files) == 0: cmb_files.insert(0, OPTION("", _value="")) cmd_filename = INPUT( _type="submit", _name="frm_filename", _title=ns.T('Start restore from local backup file'), _value=T("Start restore"), _onclick="msg_result.innerHTML='" + T("Process started. Waiting for the server to respond ...") + "';") cmd_filename["_data-theme"] = "b" cmd_filename["_data-icon"] = "check" cmd_file = INPUT( _type="submit", _name="frm_file", _title=ns.T('Upload file and Start restore'), _value=T("Upload and Start restore"), _onclick="msg_result.innerHTML='" + T("Process started. Waiting for the server to respond ...") + "';") cmd_file["_data-theme"] = "b" cmd_file["_data-icon"] = "check" cmd_file["_data-ajax"] = "false" if request.env.web2py_runtime_gae: gform = DIV( HR(), P( SPAN( T('The sqlite and Google SQL databases are created automatically. Other types of databases must be created manually before.' ))), FORM(DIV( SPAN(T('Database alias:'), _style="padding-right: 15px;padding-left: 15px;"), cmb_alias), DIV(SPAN(T('File:'), _style="padding-right: 15px;padding-left: 15px;"), INPUT(_type='file', _name='bfile', _id='bfile', _requires=IS_NOT_EMPTY()), SPAN("", _style="padding-left: 15px;"), cmd_file, _style="padding-top: 8px;"), _id="frm_upload_files", _name="frm_upload", **{"_data-ajax": "false"}), P( SPAN(msg_result, _id="msg_result", _style= "padding-left: 15px;font-style: italic;padding-top: 5px;") ), HR(), _style="font-weight: bold;", _align="left") else: gform = DIV( HR(), P( SPAN( T('The sqlite and Google SQL databases are created automatically. Other types of databases must be created manually before.' ))), FORM(DIV( SPAN(T('Database alias:'), _style="padding-right: 15px;padding-left: 15px;"), cmb_alias), DIV(SPAN(T('Filename:'), _style="padding-right: 15px;padding-left: 15px;"), cmb_files, SPAN("", _style="padding-left: 15px;"), cmd_filename, _style="padding-top: 8px;"), DIV(SPAN(T('File:'), _style="padding-right: 15px;padding-left: 15px;"), INPUT(_type='file', _name='bfile', _id='bfile', _requires=IS_NOT_EMPTY()), SPAN("", _style="padding-left: 15px;"), cmd_file, _style="padding-top: 8px;"), _id="frm_upload_files", _name="frm_upload", **{"_data-ajax": "false"}), P( SPAN(msg_result, _id="msg_result", _style= "padding-left: 15px;font-style: italic;padding-top: 5px;") ), HR(), _style="font-weight: bold;", _align="left") return dict(form=gform)