def create(): org = db.organization(session.org_id) tbl = db.desk tbl.item_list.readable = False tbl.item_list.writable = False tbl.name.requires = IS_NOT_EMPTY() form = SQLFORM(db.desk) form.add_button(T('Cancel'), URL('org', 'view', args=[org.id])) if form.process().accepted: # add the new desk to the org list desk_id = form.vars.id # add current users as the one with permission to update manage # this desk auth.add_permission( auth.user_group(auth.user.id), 'update', db.desk, desk_id) desk_list = org.desks desk_list.insert(0, desk_id) org.update_record(desks=desk_list) # return to the org desk list redirect(URL('org', 'view', args=[org.id])) return locals()
def create(): """Create a new organization""" tbl = db.organization tbl.users.readable = False tbl.users.writable = False tbl.desks.readable = False tbl.desks.writable = False tbl.name.requires = [ IS_NOT_EMPTY( error_message=T("Cannot be empty") ), IS_NOT_IN_DB( db, 'organization.name', error_message=T( "An Organization witch that name is allready in nStock"))] form = SQLFORM(tbl) form.add_button(T('Cancel'), URL('index')) if form.process().accepted: # add the new organization g_id = auth.user_group(auth.user.id) # give the user all perms over this org auth.add_permission(g_id, 'update', tbl, form.vars.id) auth.add_permission(g_id, 'read', tbl, form.vars.id) auth.add_permission(g_id, 'delete', tbl, form.vars.id) redirect(URL('index')) return locals()
def index(): item = application.getItemByUUID(request.args(0)) if item is None: raise HTTP(404) short = request.vars.short if request.vars.short is not None else False tbl = db.plugin_comment_comment tbl.item_id.default = item.unique_id form = SQLFORM( tbl, submit_button=T('Comment'), formstyle='bootstrap3_stacked') rows = db( (tbl.id > 0) & (tbl.item_id == item.unique_id) ).select(orderby=~tbl.created_on) if form.process().accepted: response.js = "jQuery('#%s').get(0).reload();" % request.cid # send notifications to the users, except the current one subject = T("Comments on %s", (item.headline,)) # get the comment body comment = tbl(form.vars.id) message = response.render( 'plugin_comment/someone_commented.txt', dict(item=item, comment=comment, user=auth.user) ) application.notifyCollaborators( item.unique_id, subject, message ) return dict(form=form, comments=rows, short=short, item=item)
def getEditgameUpdateForm (game): """ Gets an update for the edit game page. Keyword Arguments: game -- row representing the current game Return Values: formUpdate -- web2py form """ from gluon import current, redirect, URL, SQLFORM db = current.db #Hide some fields of the form hideFields (db.game, ['id', 'host_id', 'game_status', 'password']) formUpdate = SQLFORM(db.game, game.id) formUpdate.add_class('assassins-form') if formUpdate.process().accepted: resizeImage(db.game, game.id) redirect(getUrl('edit', game.id)) return formUpdate
def inserir(): u"""Permite inserir um novo registro. Um registro pode ser: - Uma notícia; - Um evento; - Um produto; - Um membro; - Um apoiador. Observação: Somente usuários com permissão de admin podem inserir novos membros e apoiadores. """ argumento = current.request.args(0) or redirect(URL('default', 'index')) lista_tabelas = ['noticias', 'eventos', 'produtos'] auth = current.globalenv['auth'] db = current.globalenv['db'] if auth.has_membership('admin'): lista_tabelas.extend(['membros', 'apoiadores']) if argumento not in lista_tabelas: current.session.flash = current.T( 'Operação não permitida a seu usuário.' ) redirect(URL('admin', 'listar', args='noticias')) form = SQLFORM( db[argumento], submit_button="Enviar", formstyle='bootstrap3_stacked') if form.process().accepted: current.response.flash = 'Registro inserido com sucesso!' elif form.errors: current.response.flash = 'Formulário contem erros' return {'argumento': argumento, 'form': form}
def create(): """Create a new organization""" tbl = db.organization tbl.users.readable = False tbl.users.writable = False tbl.desks.readable = False tbl.desks.writable = False tbl.name.requires = [ IS_NOT_EMPTY(error_message=T("Cannot be empty")), IS_NOT_IN_DB( db, 'organization.name', error_message=T( "An Organization witch that name is allready in nStock")) ] form = SQLFORM(tbl) form.add_button(T('Cancel'), URL('index')) if form.process().accepted: # add the new organization g_id = auth.user_group(auth.user.id) # give the user all perms over this org auth.add_permission(g_id, 'update', tbl, form.vars.id) auth.add_permission(g_id, 'read', tbl, form.vars.id) auth.add_permission(g_id, 'delete', tbl, form.vars.id) redirect(URL('index')) return locals()
def editform(): """ Return a sqlform object for editing the specified slide. """ sid = session.plugin_slider_sid form = SQLFORM(db.plugin_slider_slides, sid, separator='', deletable=True, showid=True) if form.process(formname='plugin_slider_slides/{}'.format(sid)).accepted: response.flash = 'The changes were recorded successfully.' elif form.errors: print('\n\nlistandedit form errors:') pprint({k: v for k, v in form.errors.items()}) print('\n\nlistandedit form vars') pprint({k: v for k, v in form.vars.items()}) print('\n\nlistandedit request vars') pprint({k: v for k, v in request.vars.items()}) response.flash = 'Sorry, there was an error processing ' \ 'the form. The changes have not been recorded.' else: pass return form
def getEditgameUpdateForm(game): """ Gets an update for the edit game page. Keyword Arguments: game -- row representing the current game Return Values: formUpdate -- web2py form """ from gluon import current, redirect, URL, SQLFORM db = current.db #Hide some fields of the form hideFields(db.game, ['id', 'host_id', 'game_status', 'password']) formUpdate = SQLFORM(db.game, game.id) formUpdate.add_class('assassins-form') if formUpdate.process().accepted: resizeImage(db.game, game.id) redirect(getUrl('edit', game.id)) return formUpdate
def diff(): item = application.getItemByUUID(request.args(0)) content = db.plugin_picture_info(item_id=item.unique_id) archive = db.plugin_picture_info_archive(request.args(1)) fields = [] fields_archived = [] fields_names = [] for f in db.plugin_picture_info: # if values diff if content[f.name] != archive[f.name]: fields_names.append(f.name) f.comment = None fields.append(f) db.plugin_picture_info_archive[f.name].comment = None fields_archived.append(db.plugin_picture_info_archive[f.name]) # build two readonly forms form_actual = SQLFORM.factory( *fields, record=content, readonly=True, showid=False, formstyle='divs' ) form_archive = SQLFORM.factory( *fields, record=archive, readonly=True, showid=False, formstyle='divs') return locals()
def index(): item = application.getItemByUUID(request.args(0)) if item is None: raise HTTP(404) short = request.vars.short if request.vars.short is not None else False tbl = db.plugin_comment_comment tbl.item_id.default = item.unique_id form = SQLFORM(tbl, submit_button=T('Comment'), formstyle='bootstrap3_stacked') rows = db((tbl.id > 0) & (tbl.item_id == item.unique_id)).select( orderby=~tbl.created_on) if form.process().accepted: response.js = "jQuery('#%s').get(0).reload();" % request.cid # send notifications to the users, except the current one subject = T("Comments on %s", (item.headline, )) # get the comment body comment = tbl(form.vars.id) message = response.render( 'plugin_comment/someone_commented.txt', dict(item=item, comment=comment, user=auth.user)) application.notifyCollaborators(item.unique_id, subject, message) return dict(form=form, comments=rows, short=short, item=item)
def index(): """ Edit content """ item = application.getItemByUUID(request.args(0)) db.plugin_picture_info.thumbnail.readable = False db.plugin_picture_info.thumbnail.writable = False db.plugin_picture_info.renditions.readable = False db.plugin_picture_info.renditions.writable = False content = db.plugin_picture_info(item_id=item.unique_id) form = SQLFORM( db.plugin_picture_info, record=content, showid=False, submit_button=T('Save')) if form.process().accepted: application.notifyChanges(item.unique_id) application.indexItem(item.unique_id) response.flash = None return dict(form=form, item=item, content=content)
def venda(): if not session.flashed: response.flash = T('Bem vindo a tela de vendas!') title = "Venda" ####SQL#################################################### ####################################################### #aqui ele formata tudo sozinho e ainda envia para o banco sozinho também #mas não mostra a mensagem de falha ou aceitação sozinho venda_sqlform = SQLFORM(db2.venda) if venda_sqlform.accepts(request,session): response.flash = 'Form accepted' formulario = db2().select(db2.venda.ALL).last() fecha_venda(formulario) elif venda_sqlform.errors: response.flash = 'Form has errors' else: response.flash = 'Please fill the form' form_venda = detalhes_geral(db2.venda, 2) (form_crud,table_crud) = pesquisa_geral(db2.venda) return locals()
def vendedor(): title = "Cadastro de Vendedores" #lista todos os carros na tela vendedor_grid = SQLFORM.smartgrid(db2.vendedor) #CRUD #aqui ele formata tudo sozinho e ainda envia para o banco sozinho também #mostra a mensagem de falha sozinho vendedor_crud = crud.create(db2.vendedor) ####SQL#################################################### ####################################################### #aqui ele formata tudo sozinho e ainda envia para o banco sozinho também #mas não mostra a mensagem de falha ou aceitação sozinho vendedor_sqlform = SQLFORM(db2.vendedor) if vendedor_sqlform.accepts(request,session): response.flash = 'Form accepted' elif vendedor_sqlform.errors: response.flash = 'Form has errors' else: response.flash = 'Please fill the form' form_vendedor = detalhes_geral(db2.vendedor, 1) (form_crud,table_crud) = pesquisa_geral(db2.vendedor) return locals()
def add_rendition(): item = application.getItemByUUID(request.args(0)) content = db.plugin_picture_info(item_id=item.unique_id) form = SQLFORM(db.plugin_picture_rendition) if form.process().accepted: r_id = form.vars.id rend = db.plugin_picture_rendition(r_id) (filename, stream) = db.plugin_picture_rendition.picture.retrieve(rend.picture) filename = stream.name im = Image.open(filename) # update rendition with image info rend.height = im.height rend.width = im.width rend.format = im.format rend.color = im.mode rend.update_record() # append this rendition to the item content content.renditions.append(r_id) content.update_record() redirect(application.getItemURL(item.unique_id)) return locals()
def diff(): item = application.getItemByUUID(request.args(0)) if item is None: raise HTTP(404) content = db.plugin_text_text(item_id=item.unique_id) archive = db.plugin_text_text_archive(request.args(1)) fields = [] fields_archived = [] fields_names = [] for f in db.plugin_text_text: # if values diff if content[f.name] != archive[f.name]: fields_names.append(f.name) f.comment = None fields.append(f) db.plugin_text_text_archive[f.name].comment = None fields_archived.append(db.plugin_text_text_archive[f.name]) # build two readonly forms form_actual = SQLFORM.factory(*fields, record=content, readonly=True, showid=False, formstyle='divs') form_archive = SQLFORM.factory(*fields, record=archive, readonly=True, showid=False, formstyle='divs') return locals()
def add_rendition(): item = application.getItemByUUID(request.args(0)) content = db.plugin_picture_info(item_id=item.unique_id) form = SQLFORM(db.plugin_picture_rendition) if form.process().accepted: r_id = form.vars.id rend = db.plugin_picture_rendition(r_id) (filename, stream) = db.plugin_picture_rendition.picture.retrieve( rend.picture) filename = stream.name im = Image.open(filename) # update rendition with image info rend.height = im.height rend.width = im.width rend.format = im.format rend.color = im.mode rend.update_record() # append this rendition to the item content content.renditions.append(r_id) content.update_record() redirect(application.getItemURL(item.unique_id)) return locals()
def edit(): dash = db.dashboard(request.args(0)) db.dashboard.item_list.readable = False db.dashboard.item_list.writable = False form = SQLFORM(db.dashboard, record=dash, showid=False) if form.process().accepted: redirect(URL('index', args=[dash.id])) return locals()
def inserir(): """Insere um novo banner.""" db = current.globalenv['db'] form = SQLFORM( db.carousel, submit_button="Enviar", formstyle='bootstrap3_stacked') if form.process().accepted: current.response.flash = 'Registro inserido com sucesso!' elif form.errors: current.response.flash = 'Formulário contem erros' return {'form': form}
def detalhes_geral(tabela, tb_id): registro_geral = tabela(tb_id) or redirect(URL('Inicio')) form_geral =SQLFORM(tabela,registro_geral,deletable=True,upload=URL('veiculo','download')) if form_geral.accepts(request.vars,session): response.flash = 'Sucesso' elif form_geral.errors: response.flash = 'Erro' return form_geral
def edit(): desk = db.desk(request.args(0)) session.desk_id = desk.id db.desk.item_list.readable = False db.desk.item_list.writable = False form = SQLFORM(db.desk, record=desk, showid=False) if form.process().accepted: redirect(URL('index', args=[desk.id])) return locals()
def index(): """ Edit/Show package content """ pkg_item = application.getItemByUUID(request.args(0)) content = db.plugin_package_content(item_id=pkg_item.unique_id) form = SQLFORM(db.plugin_package_content, record=content, showid=False) if form.process().accepted: application.indexItem(pkg_item.unique_id) redirect(URL('default', 'index')) return locals()
def edit(): org = db.organization(request.args(0)) tbl = db.organization tbl.users.readable = False tbl.users.writable = False tbl.desks.readable = False tbl.desks.writable = False tbl.name.requires = [IS_NOT_EMPTY()] # edit form form = SQLFORM(db.organization, record=org, showid=False) if form.process().accepted: redirect(URL('view', args=[org.id])) return locals()
def create(): """ Show the creation form of the text item. """ fields = [ db.item.headline, db.item.keywords, db.item.genre, db.item.item_type, db.plugin_text_text.body ] db.item.item_type.default = 'text' db.item.item_type.writable = False db.item.item_type.readable = False form = SQLFORM.factory(*fields) if form.process().accepted: item_id = application.createItem('text', form.vars) form.vars.item_id = item_id db.plugin_text_text.insert( **db.plugin_text_text._filter_fields(form.vars)) application.indexItem(item_id) redirect(URL('default', 'index.html')) return locals()
def bulk_update(): """ Controller function to perform a programmatic update to a field in one table. """ response = current.response db = current.db myrecs = None form = SQLFORM.factory( Field('table', requires=IS_IN_SET(db.tables)), Field('field'), Field('query'), Field('new_value')) if form.process().accepted: query = eval(form.vars.query) try: recs = db(query) recs.update(**{form.vars.field: form.vars.new_value}) myrecs = recs.select() response.flash = 'update succeeded' except Exception: print traceback.format_exc(5) elif form.errors: myrecs = BEAUTIFY(form.errors) response.flash = 'form has errors' return form, myrecs
def grid(db): """ Return an SQLFORM.grid to manage poems. """ createargs = editargs = viewargs = { 'fields': ['chapter', 'published', 'intro_hanzi', 'intro_en'] } fields = [ db.poem.chapter, db.poem.published, db.poem.intro_hanzi, db.poem.intro_en ] maxtextlengths = {'poem.published': 50} onupdate = lambda form: decache(int(form.vars.chapter), db) db.poem.published.represent = lambda value, row: value.strftime(date_format ) db.poem.chapter.requires = IS_IN_SET(range(1, 82), zero=None) grid = SQLFORM.grid(db.poem, createargs=createargs, csv=False, editargs=editargs, fields=fields, maxtextlengths=maxtextlengths, oncreate=onupdate, onupdate=onupdate, orderby=db.poem.chapter, paginate=None, searchable=False, viewargs=viewargs) return grid
def send_email(): title = 'Contato' form = SQLFORM.factory( Field('name', requires=IS_NOT_EMPTY()), Field('email', requires =[ IS_EMAIL(error_message='invalid email!'), IS_NOT_EMPTY() ]), Field('subject', requires=IS_NOT_EMPTY()), Field('message', requires=IS_NOT_EMPTY(), type='text') ) if form.process().accepted: session.name = form.vars.name session.email = form.vars.email session.subject = form.vars.subject session.message = form.vars.message x = mails.send(to=['*****@*****.**'], subject='loja de carros', message= "Olá esse é um email de teste da lja de carros.\nName:"+ session.name+" \nEmail : " + session.email +"\nSubject : "+session.subject +"\nMessage : "+session.message+ ".\n " ) if x == True: response.flash = 'email sent sucessfully.' else: response.flash = 'fail to send email sorry!' #response.flash = 'form accepted.' elif form.errors: response.flash='form has errors.' form_carro = detalhes_geral(db2.carro, 2) (form_crud,table_crud) = pesquisa_geral(db2.carro) return locals()
def reportcontent(self): if not self.db.auth.user: vrs = { "_next": self.CURL('page', 'reportcontent', args=self.db.request.args) } redirect(self.CURL('person', 'account', args=['login'], vars=vrs)) self.response.meta.title = "%s | %s" % ( self.db.T("Report content"), self.db.config.meta.title, ) self.db.Report.content_type.default = self.db.T( self.db.request.args(0)) self.db.Report.item_id.default = int(self.db.request.args(1)) self.db.Report.slug.default = self.db.request.args(2) self.db.Report.content_type.writable = \ self.db.Report.item_id.writable = \ self.db.Report.slug.writable = False self.context.form = SQLFORM(self.db.Report, formstyle='divs') self.context.form.insert(0, H1(self.db.T("Report content or user"))) if self.context.form.process().accepted: self.db.response.flash = self.db.T( "Thank you for reporting this content")
def create(): fields = [] fld_headline = db.item.headline fields.extend([fld_headline, db.item.keywords, db.item.genre]) fdl_item_type = db.item.item_type fdl_item_type.writable = False fdl_item_type.readable = False fdl_item_type.default = 'photoset' form = SQLFORM.factory( *fields, table_name='plugin_photo_set' # to allow the correct form name ) if form.process(dbio=False).accepted: # item_id = CT_REG.photoset.create_item(form.vars) item_id = application.createItem('photoset', form.vars) form.vars.item_id = item_id if session.plugin_photoset: form.vars.photoset = session.plugin_photoset.photos else: form.vars.phoset = [] db.plugin_photoset_content.insert( **db.plugin_photoset_content._filter_fields( form.vars ) ) application.indexItem(item_id) session.plugin_photoset = None redirect(URL('default', 'index.html')) return locals()
def contact(): """ Controller for a simple contact form. """ mail = current.mail keydata = {} with open('applications/grammateus3/private/app.keys', 'r') as keyfile: for line in keyfile: k, v = line.split() keydata[k] = v form = SQLFORM.factory(Field('your_email_address', requires=IS_EMAIL()), Field('message_title', requires=IS_NOT_EMPTY()), Field('message', 'text', requires=IS_NOT_EMPTY()), submit_button='Send message', separator=' ') captcha = Recaptcha2(request, keydata['captcha_public_key'], keydata['captcha_private_key']) form.element('table').insert(-1, TR('', captcha, '')) if form.process().accepted: if mail.send(to='*****@*****.**', reply_to=form.vars.your_email_address, subject='OCP Contact: {}'.format(form.vars.message_title), message=form.vars.message): response.flash = 'Thank you for your message.' response.js = "jQuery('#%s').hide()" % request.cid else: form.errors.your_email = "Sorry, we were unable to send the email" return dict(form=form)
def all_items(): """ Show user items list """ if type(request.vars.q) is list: # in the case of being loaded from a query string # use only the last valor from q request.vars.q = request.vars.q[-1] request.vars.q = None if request.vars.q == '' else request.vars.q if request.vars.q is not None: ids = Whoosh().search(request.vars.q) query = db.item.unique_id.belongs(ids) else: query = (db.item.id > 0) query &= ( auth.accessible_query('collaborator', db.item) | auth.accessible_query('owner', db.item)) grid = SQLFORM.grid( query, orderby=[~db.item.created_on], create=False, csv=False, paginate=6, ) return dict(grid=grid)
def handle_upload(self): """ Get an upload from CKEditor and returns the new filename. Get an upload from CKEditor and returns the new filename that can then be inserted into a database. Returns (new_filename, old_filename, length, mime_type) """ upload = current.request.vars.upload path = os.path.join(current.request.folder, 'uploads') if upload is not None: if hasattr(upload, 'file'): form = SQLFORM.factory( Field('upload', 'upload', requires=IS_NOT_EMPTY(), uploadfs=self.settings.uploadfs, uploadfolder=path), table_name=self.settings.table_upload_name, ) old_filename = upload.filename new_filename = form.table.upload.store(upload.file, upload.filename) if self.settings.uploadfs: length = self.settings.uploadfs.getsize(new_filename) else: length = os.path.getsize(os.path.join(path, new_filename)) mime_type = upload.headers['content-type'] return (new_filename, old_filename, length, mime_type) else: raise HTTP(401, 'Upload is not proper type.') else: raise HTTP(401, 'Missing required upload.')
def projeto(): u"""Editar informações sobre o projeto marolo. Permite que um usuário com permissão de admin edite as informações sobre o projeto. """ path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/../views/default/sobre_projeto.html', 'r') as arq: sobre_projeto = arq.read() ckeditor = current.globalenv['ckeditor'] form = SQLFORM.factory( Field( 'texto', 'text', widget=ckeditor.widget, default=sobre_projeto, requires=IS_NOT_EMPTY() ), hideerror=True, message_onfailure=current.T('O conteúdo não pode ser vazio.') ) form.elements('label', replace=None) if form.process().accepted: with open(path + '/../views/default/sobre_projeto.html', 'w') as arq: arq.write(form.vars.texto) current.session.flash = current.T( 'Sobre o projeto editado com sucesso!' ) redirect(URL('admin', 'listar', args='noticias')) return {'form': form}
def delete(): desk = db.desk(request.args(0)) session.desk_id = desk.id db.desk.item_list.readable = False db.desk.item_list.writable = False form = SQLFORM.confirm( T("Are you sure?"), {T('Cancel'): URL('index', args=[desk.id])}) if form.accepted: # empty move all the items in the desk to the owners desk for item_id in desk.item_list: item = db.item(item_id) owner = db.auth_user(item.created_by) owner_desk = application.getUserDesk(user=owner) owner_desk_items = owner_desk.item_list owner_desk_items.append(item_id) owner_desk.update_record(item_list=owner_desk_items) # remove desk from org org = db( db.organization.desks.contains(desk.id) ).select().first() desk_list = org.desks desk_list.remove(desk.id) org.update_record(desks=desk_list) # delete the desk from db. del db.desk[desk.id] # cleanup context session.desk_id = None # go to org view redirect(URL('org','view', args=[org.id])) return locals()
def create_new(self): # permission is checked here if self.auth.has_membership("author", self.auth.user_id): self.db.Post.author.default = self.auth.user_id self.context.form = SQLFORM(self.db.Post, formstyle='divs').process(onsuccess=lambda form: redirect(URL('show', args=form.vars.id))) else: self.context.form = "You can't post, only logged in users, members of 'author' group can post"
def delete(): desk = db.desk(request.args(0)) session.desk_id = desk.id db.desk.item_list.readable = False db.desk.item_list.writable = False form = SQLFORM.confirm(T("Are you sure?"), {T('Cancel'): URL('index', args=[desk.id])}) if form.accepted: # empty move all the items in the desk to the owners desk for item_id in desk.item_list: item = db.item(item_id) owner = db.auth_user(item.created_by) owner_desk = application.getUserDesk(user=owner) owner_desk_items = owner_desk.item_list owner_desk_items.append(item_id) owner_desk.update_record(item_list=owner_desk_items) # remove desk from org org = db(db.organization.desks.contains(desk.id)).select().first() desk_list = org.desks desk_list.remove(desk.id) org.update_record(desks=desk_list) # delete the desk from db. del db.desk[desk.id] # cleanup context session.desk_id = None # go to org view redirect(URL('org', 'view', args=[org.id])) return locals()
def edit(self): self.get() self.context.form = SQLFORM(self.db.Page, self.context.page, formstyle='divs') if self.context.form.process().accepted: redirect(self.CURL("show", args=self.context.form.vars.id))
def load_items(): """Show the item list of this dashboard""" dash = db.dashboard(request.args(0)) # session.dashboard = dash.id request.vars.q = None if request.vars.q == '' else request.vars.q if request.vars.q is not None: ids = Whoosh().search(request.vars.q) query = db.item.unique_id.belongs(ids) else: query = (db.item.id > 0) query &= ( auth.accessible_query('collaborator', db.item) | auth.accessible_query('owner', db.item)) query &= db.dashboard.item_list.contains(db.item.unique_id) query &= (db.dashboard.id == dash.id) grid = SQLFORM.grid( query, args=request.args[:1], orderby=[~db.item.created_on], create=False, csv=False, paginate=6, ) response.title = dash.name response.js = "jQuery('#dashboard_cmp').get(0).reload();" return dict(grid=grid, current_dash=dash)
def share(): """ Show the list of desk to with the item can be push """ item = application.getItemByUUID(request.args(0)) if item is None: raise HTTP(404) query = (db.desk.id != session.desk_id) query &= auth.accessible_query('push_items', db.desk) posible_desk = db(query).select() fld_to_desk = Field('to_desk', 'integer') fld_to_desk.label = T("Push to") fld_to_desk.comment = T("Select where to push the item") fld_to_desk.requires = IS_IN_SET([(desk.id, desk.name) for desk in posible_desk]) form = SQLFORM.factory(fld_to_desk, submit_button=T("Send"), table_name='share') if form.process().accepted: # send the item to the selected desk ct = application.getContentType(item.item_type) ct.shareItem(item.unique_id, session.desk_id, form.vars.to_desk) response.js = "$('#metaModal').modal('hide');" return locals()
def contact(): """ Controller for a simple contact form. """ mail = current.mail keydata = {} with open('applications/grammateus3/private/app.keys', 'r') as keyfile: for line in keyfile: k, v = line.split() keydata[k] = v form = SQLFORM.factory(Field('your_email_address', requires=IS_EMAIL()), Field('message_title', requires=IS_NOT_EMPTY()), Field('message', 'text', requires=IS_NOT_EMPTY()), submit_button='Send message', separator=' ') captcha = Recaptcha2(request, keydata['captcha_public_key'], keydata['captcha_private_key']) form.element('table').insert(-1, TR('', captcha, '')) if form.process().accepted: if mail.send(to='*****@*****.**', subject='OCP Contact: {}'.format(form.vars.message_title), message=form.vars.message): response.flash = 'Thank you for your message.' response.js = "jQuery('#%s').hide()" % request.cid else: form.errors.your_email = "Sorry, we were unable to send the email" return dict(form=form)
def create(): """ Show the creation form of the text item. """ fields = [ db.item.headline, db.item.keywords, db.item.genre, db.item.item_type, # db.plugin_text_text.body ] db.item.item_type.default = 'text' db.item.item_type.writable = False db.item.item_type.readable = False form = SQLFORM.factory(*fields, submit_button=T("Next")) if form.process().accepted: item_id = application.createItem('text', form.vars) form.vars.item_id = item_id db.plugin_text_text.insert( **db.plugin_text_text._filter_fields(form.vars)) application.indexItem(item_id) redirect(URL('index.html', args=[item_id])) return locals()
def meta(): """ Edit/Show item metadata info """ item = application.getItemByUUID(request.args(0)) if item is None: raise HTTP(404) contentType = application.getContentType(item.item_type) l_names = [ (r.language_tag, r.english_name) for r in db( db.languages.id > 0 ).select(orderby=db.languages.english_name) ] db.item.language_tag.requires = IS_IN_SET( l_names, zero=None ) # issue #5 hidde some fields from metadata db.item.provider.readable = False db.item.provider.writable = False db.item.provider_service.readable = False db.item.provider_service.writable = False db.item.copyright_holder.readable = False db.item.copyright_holder.writable = False db.item.copyright_url.readable = False db.item.copyright_url.writable = False db.item.copyright_notice.readable = False db.item.copyright_notice.writable = False db.item.pubstatus.readable = False db.item.pubstatus.writable = False form = SQLFORM(db.item, record=item) if form.process().accepted: # session.flash = "Done !" # send an email to all the users who has access to this item application.notifyChanges(item.unique_id) application.indexItem(item.unique_id) if request.ajax: response.js = "$('#metaModal').modal('hide');" else: redirect(application.getItemURL(item.unique_id)) return locals()
def edit(self): self.context.customfield = customfield self.get() self.db.article.thumbnail.compute = lambda r: THUMB2( r['picture'], gae=self.request.env.web2py_runtime_gae) self.db.article.medium_thumbnail.compute = lambda r: THUMB2( r['picture'], gae=self.request.env.web2py_runtime_gae, nx=400, ny=400, name='medium_thumb') self.context.article_form = SQLFORM(self.db.article, self.context.article) content, article_data = self.get_content( self.context.article.content_type_id.classname, self.context.article.id) if self.context.article_form.process().accepted: article_data.update_record( **content.entity._filter_fields(self.request.vars)) self.new_article_event( 'update_article', data={ 'event_link': "%s/%s" % (self.context.article.id, IS_SLUG()( self.context.article_form.vars.title)[0]), 'event_text': self.context.article_form.vars.description, 'event_to': "%s (%s)" % (self.context.article.content_type_id.title, self.context.article.title), 'event_image': self.get_image( self.context.article.thumbnail, self.context.article.content_type_id.identifier) }) self.session.flash = self.T( "%s updated." % self.context.article.content_type_id.title) self.context.article.update_record(search_index="|".join( str(value) for value in self.request.vars.values())) redirect( self.CURL('article', 'show', args=[ self.context.article.id, IS_SLUG()(self.request.vars.title)[0] ])) self.context.content_form = SQLFORM(content.entity, article_data)
def share(): """ Show the list of desk to with the item can be push """ item = application.getItemByUUID(request.args(0)) if item is None: raise HTTP(404) query = (db.desk.id != session.desk_id) query &= auth.accessible_query('push_items', db.desk) posible_desk = db(query).select() fld_to_desk = Field('to_desk', 'integer') fld_to_desk.label = T("Push to organization desk") fld_to_desk.comment = T("Select where to push the item") fld_to_desk.requires = IS_EMPTY_OR( IS_IN_SET([(desk.id, desk.name) for desk in posible_desk])) fld_personal_desk = Field('to_person_desk', 'integer') fld_personal_desk.label = T("Push to other person desk") fld_personal_desk.comment = T("Select a person from the list.") # list of person on orgs persons = [] # search up all the persons orgs = db(db.organization.users.contains(auth.user.id)).select() for org in orgs: x = [db.auth_user(id=y) for y in org.users if y != auth.user.id] persons.extend(x) persons = list(set(persons)) fld_personal_desk.requires = IS_EMPTY_OR( IS_IN_SET([(per.id, "{} {}".format(per.first_name, per.last_name)) for per in persons])) fld_cond = Field('cond', 'boolean', default=False) fld_cond.label = T('To other person?') form = SQLFORM.factory(fld_to_desk, fld_personal_desk, fld_cond, submit_button=T("Send"), table_name='share') if form.process().accepted: src = session.desk_id if form.vars.cond: # send the item to other user other_user = db.auth_user(form.vars.to_person_desk) target = application.getUserDesk(other_user).id else: # send the item to the selected desk target = form.vars.to_desk if target: ct = application.getContentType(item.item_type) ct.shareItem(item.unique_id, src, target) response.js = "$('#metaModal').modal('hide');" response.flash = None return locals()
def Inicio(): session.flashed = False #####classes################# myinstance = MyClass(3, 4) print myinstance.add() b = MyList(3, 4, 5) print b[1] b.a[1] = 7 print b.a ############################## if not session.flashed: response.flash = T('Bem vindo a loja de carros!') #response.write('Venha conhecer nossos carros!!!') ############################### agora = request.now #lista todos os carros na tela #car_smartgrid = SQLFORM.smartgrid(db2.carro) #lista todos os carros na tela car_grid = SQLFORM.grid(db2.carro) #contador de sessão session.counter = (session.counter or 0) + 1 counter = session.counter #mostrar o nome do usuário na tela if auth2.user: visitor_name = auth2.user.first_name else: visitor_name = 'nenhum' table_hora = [] table_hora.append(TR('Hora Atual:',agora)) table_hora.append(TR('Visitante:',visitor_name)) table_hora.append(TR('Número de visitas:',counter)) table = TABLE(table_hora) form_hora = FORM(table) order = db2.carro.marca #selecionar apenas os que possuem fotos registros = db2(db2.carro.foto!=None).select(orderby=order) form_teste = FORM(registros) form_carro = detalhes_geral(db2.carro, 2) (form_crud,table_crud) = pesquisa_geral(db2.carro) title = "Loja de Carros" # showcase = SHOWCASE(registros) return locals()
def index(): """ Edit/Show package content """ pkg_item = application.getItemByUUID(request.args(0)) content = db.plugin_package_content(item_id=pkg_item.unique_id) form = SQLFORM( db.plugin_package_content, record=content, showid=False) if form.process().accepted: application.indexItem(pkg_item.unique_id) redirect(URL('default', 'index')) return locals()
def linked_create_form(): """ creates a form to insert a new entry into the linked table which populates the ajaxSelect widget """ print 'Starting linked_create_form' try: tablename = request.args[0] fieldname = request.args[1] wrappername = request.vars['wrappername'] table = db[tablename] field = table[fieldname] linktable = get_linktable(field) formname = '{}_create'.format(wrappername) form = SQLFORM(db[linktable]) comp_url = URL('plugin_ajaxselect', 'set_widget.load', args=[tablename, fieldname], vars=request.vars) if form.process(formname=formname).accepted: response.flash = 'form accepted' response.js = "window.setTimeout(" \ "web2py_component('{}', '{}'), " \ "500);".format(comp_url, wrappername) print 'linked create form accepted' print 'linked create form vars:' pprint(form.vars) if form.errors: response.error = 'form was not processed' response.flash = 'form was not processed' print 'error processing linked_create_form' print form.errors else: print 'form not processed but no errors' pass except Exception: import traceback print traceback.format_exc(5) form = traceback.format_exc(5) return dict(form=form)
def edit_post(self, post_id): post = self.db.Post[post_id] # permission is checked here if not post or post.author != self.auth.user_id: redirect(URL("post", "index")) self.context.form = SQLFORM( self.db.Post, post.id, formstyle='divs').process(onsuccess=lambda form: redirect( URL('show', args=form.vars.id)))
def edit_form(): item = application.getItemByUUID(request.args(0)) content = db.plugin_photoset_content(item_id=item.unique_id) db.plugin_photoset_content.photoset.readable = False db.plugin_photoset_content.photoset.writable = False db.plugin_photoset_content.item_id.readable = False db.plugin_photoset_content.item_id.writable = False form = SQLFORM(db.plugin_photoset_content, record=content, showid=False, submit_button=T('Save')) if form.process().accepted: application.notifyChanges(item.unique_id) application.indexItem(item.unique_id) response.flash = T('Saved') return form
def meta(): """ Edit/Show item metadata info """ item = application.getItemByUUID(request.args(0)) if item is None: raise HTTP(404) contentType = application.getContentType(item.item_type) l_names = [(r.language_tag, r.english_name) for r in db( db.languages.id > 0).select(orderby=db.languages.english_name)] db.item.language_tag.requires = IS_IN_SET(l_names, zero=None) # issue #5 hidde some fields from metadata db.item.provider.readable = False db.item.provider.writable = False db.item.provider_service.readable = False db.item.provider_service.writable = False db.item.copyright_holder.readable = False db.item.copyright_holder.writable = False db.item.copyright_url.readable = False db.item.copyright_url.writable = False db.item.copyright_notice.readable = False db.item.copyright_notice.writable = False db.item.pubstatus.readable = False db.item.pubstatus.writable = False form = SQLFORM(db.item, record=item) if form.process().accepted: # session.flash = "Done !" # send an email to all the users who has access to this item application.notifyChanges(item.unique_id) application.indexItem(item.unique_id) if request.ajax: response.js = "$('#metaModal').modal('hide');" else: redirect(application.getItemURL(item.unique_id)) return locals()
def linked_edit_form(): """ creates a form to edit, update, or delete an intry in the linked table which populates the AjaxSelect widget. """ try: tablename = request.args[0] fieldname = request.args[1] table = db[tablename] field = table[fieldname] linktable = get_linktable(field) this_row = request.args[2] wrappername = request.vars['wrappername'] formname = '{}/edit'.format(tablename) form = SQLFORM(db[linktable], this_row) comp_url = URL('plugin_ajaxselect', 'set_widget.load', args=[tablename, fieldname], vars=request.vars) if form.process(formname=formname).accepted: response.flash = 'form accepted' response.js = "web2py_component('%s', '%s');" % (comp_url, wrappername) if form.errors: response.error = 'form was not processed' print('error processing linked_create_form') print(form.errors) else: pass except Exception: import traceback print('error in whole of linked_edit_form') print(traceback.format_exc(5)) form = traceback.format_exc(5) return {'form': form}
def diff(): """ Show the diff betwen the actual item and the archive one """ item = application.getItemByUUID(request.args(0)) if item is None: raise HTTP(404) item_archive = db.item_archive(request.args(1)) if item_archive is None: raise HTTP(503) fields = [] fields_archived = [] # allow view of administrative metadata db.item.modified_by.readable = True db.item.modified_on.readable = True db.item_archive.modified_by.readable = True db.item_archive.modified_on.readable = True for f in db.item: if item[f.name] != item_archive[f.name]: f.comment = None fields.append(f) db.item_archive[f.name].comment = None fields_archived.append(db.item_archive[f.name]) # build two readonly forms form_actual = SQLFORM.factory(*fields, record=item, readonly=True, showid=False, formstyle='divs') form_archive = SQLFORM.factory(*fields_archived, record=item_archive, readonly=True, showid=False, formstyle='divs') return dict(item=item, form_actual=form_actual, form_archive=form_archive)
def index(): """ Edit content """ item = application.getItemByUUID(request.args(0)) if item is None: raise HTTP(404) content = db.plugin_text_text(item_id=item.unique_id) form = SQLFORM(db.plugin_text_text, record=content, showid=False, submit_button=T('Save')) if form.process().accepted: application.notifyChanges(item.unique_id) application.indexItem(item.unique_id) redirect(application.getItemURL(item.unique_id)) response.flash = T('Done') return dict(form=form, item=item, content=content)
def gather_from_field(tablename, fieldname, regex_str, exclude, filter_func=None, unique=True): """ Return a list of all strings satisfying the supplied regex. The fieldnames argument should be a list, so that multiple target fields can be searched at once. The optional 'unique' keyword argument determines whether duplicates will be removed from the list. (Defaults to True.) The optional 'filterfunc' keyword argument allows a function to be passed which which will be used to alter the gathered strings. This alteration will happen before duplicate values are removed. So, for example, the strings can be normalized for case or accent characters if those variations are not significant. """ db = current.db form = SQLFORM.factory(Field('target_field'), Field('target_table'), Field('filter_func'), Field('trans_func'), Field('write_table'), Field('write_field'), Field('unique', 'boolean', default=True), Field('testing', 'boolean', default=True)) if form.process().accepted: vv = form.vars filter_func = eval(vv.filter_func) if vv.filter_func else None trans_func = eval(vv.trans_func) if vv.trans_func else None items = [] rows = db(db[vv.target_table].id > 0).select() for r in rows: items.append(r['target_field']) if filter_func: items = filter(filter_func, items) if trans_func: items = [trans_func(i) for i in items] if vv.unique: items = list(set(items)) items = [i for i in items if i not in exclude] elif form.errors: items = BEAUTIFY(form.errors) return form, items
def members(): org = db.organization(request.args(0)) if not request.args(1): fld_email = Field('email', 'string', label=T("Email")) fld_email.requires = IS_EMAIL() form = SQLFORM.factory(fld_email, formstyle='bootstrap3_inline', submit_button=T("Add user"), table_name='members') if form.process().accepted: u = db.auth_user(email=form.vars.email) if u is not None: # create new share if u.id in org.users: form.errors.email = T( "The user is already in the organization") else: user_list = org.users user_list.insert(0, u.id) org.update_record(users=user_list) g_id = auth.user_group(u.id) auth.add_permission(g_id, 'read', db.organization, org.id) else: # no user with that email response.flash = "" form.errors.email = T("The user don't exists on this system") elif request.args(1) == 'delete': # remove the user on args(2) from the org members list # TODO: remove else any perms on the org desks user_to_remove = db.auth_user(request.args(2)) if user_to_remove is not None: user_list = org.users user_list.remove(user_to_remove.id) org.update_record(users=user_list) # remove perms over the org auth.del_permission(auth.user_group(user_to_remove.id), 'read', db.organization, org.id) # remove, also, all rights over the desks in the org. desk_perms = [ 'read_desk', 'update_items', 'push_items', 'update_desk' ] for desk_id in org.desks: for perm in desk_perms: auth.del_permission(auth.user_group(user_to_remove.id), perm, db.desk, desk_id) redirect(URL('org', 'members', args=[org.id])) return locals()
def add_rendition(): item = application.getItemByUUID(request.args(0)) content = db.plugin_picture_info(item_id=item.unique_id) db.plugin_picture_rendition.thumbnail.writable = False db.plugin_picture_rendition.thumbnail.readable = False form = SQLFORM(db.plugin_picture_rendition) if form.process().accepted: r_id = form.vars.id rend = db.plugin_picture_rendition(r_id) (filename, stream) = db.plugin_picture_rendition.picture.retrieve( rend.picture) filename = stream.name im = Image.open(filename) # update rendition with image info rend.width, rend.height = im.size rend.format = im.format rend.color = im.mode rend.update_record() # -------------------------------- size = (700, 700) im.thumbnail(size) fl = NamedTemporaryFile(suffix=".jpg", delete=True) fl.close() im.save(fl.name, "JPEG") store_tumb = db.plugin_picture_rendition.thumbnail.store( open(fl.name, 'rb'), fl.name) os.unlink(fl.name) # cleanup rend.update_record( thumbnail=store_tumb ) # append this rendition to the item content content.renditions.append(r_id) content.update_record() redirect(application.getItemURL(item.unique_id)) return locals()