def layout(item): """ Language menu layout options for each entry: - lang_code: the language code - lang_name: the language name option for the menu - current_language: code of the current language """ if item.enabled: if item.components: # The language menu itself current_language = current.T.accepted_language items = item.render_components() select = SELECT( items, value=current_language, _name="_language", # @ToDo T: _title="Language Selection", _onchange= "S3.reloadWithQueryStringVars({'_language':$(this).val()});" ) form = FORM(select, _class="language-selector", _name="_language", _action="", _method="get") return form else: # A language entry return OPTION(item.opts.lang_name, _value=item.opts.lang_code) else: return None
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 search(self): q = self.request.vars.q or None self.context.form = FORM(INPUT(_type="text", _name="q", _id="q", _value=q or ''), _method="GET") if q: query = (self.db.Article.search_index.like("%" + q + "%")) | ( self.db.Article.tags.contains(q)) self.context.results = self.db(query).select() else: self.context.results = []
def index(): log('acceso') # menu favoritos form = CENTER( FORM(DIV(I(' Personal', _class='fa fa-ticket fa-2x', _id='tit_minigrid'), DIV(grand_button('empleados', 'admin_tabla', 'fa-cart-plus', vars={'tabla': 'empleado'}), grand_button('ver marcadas', 'admin_tabla', 'fa-th-large'), grand_button('informe mes empleado', 'informe_mes_empleado', 'fa-truck'), _id='mini_grid'), _id='indexdiv'), _id='panel_grid')) return dict(form=form)
def get_html(self): card_content = DIV(FORM( INPUT(_type="text", _name="q", _placeholder="Type some tag...", _autocomplete="off"), INPUT(_type="submit", _value="Search", _class="btn btn-default"), _action=URL("problems", "search"), _method="GET", _class="col offset-s1 s10 search-by-tag-card-submit"), _class="row") card_html = BaseCard.get_html( self, **dict(card_title=self.card_title, card_content=card_content, cta_links=self.get_cta_html(), card_color_class="white", card_text_color_class="black-text")) return card_html
def getEditgameBtn(game, user): """ Gets a dictionary of buttons that do stuff for the edit game page. Keyword Arguments: game -- row representing the current game user -- row representing the current user Return Values: btn -- dictionary of web2py forms -- 'back' Back To Game -- 'delete' Delete Game """ from gluon import URL, INPUT, FORM, A, redirect btn = {'back': 'back', 'delete': 'delete'} link = A('Back to Game', _class='btn btn-large btn-inverse btn-block', _href=URL('default', 'game', args=game.id)) btn['back'] = link button = INPUT( _type='submit', _value='(Host) Delete Game', _class='btn btn-small btn-block abtn-small', _onclick= 'return confirm(\'Are you sure you want to delete this game?\');') formDelete = FORM(button) btn['delete'] = formDelete if btn['delete'].process().accepted: deleteGame(game.id, user) redirect(URL('default', 'current')) return btn
def apply_method(r, **attr): """ Apply method. @param r: the S3Request @param attr: controller options for this request """ if r.representation == "html": T = current.T response = current.response tracker = S3Trackable(r.table, record_id=r.id) title = T("Check-Out") # Give the user a form to check-out # Test the formstyle formstyle = current.deployment_settings.get_ui_formstyle() row = formstyle("test", "test", "test", "test") if isinstance(row, tuple): # Formstyle with separate row for label (e.g. default Eden formstyle) tuple_rows = True else: # Formstyle with just a single row (e.g. Bootstrap, Foundation or DRRPP) tuple_rows = False form_rows = [] comment = "" _id = "submit" label = "" widget = INPUT(_type="submit", _value=T("Check-Out")) row = formstyle("%s__row" % _id, label, widget, comment) if tuple_rows: form_rows.append(row[0]) form_rows.append(row[1]) else: form_rows.append(row) if tuple_rows: # Assume TRs form = FORM(TABLE(*form_rows)) else: form = FORM(*form_rows) if form.accepts(current.request.vars, current.session): # Check-Out # We're not Checking-out in S3Track terms (that's about removing an interlock with another object) # What we're doing is saying that we're now back at our base location #tracker.check_out() #timestmp = form_vars.get("timestmp", None) #if timestmp: # # @ToDo: Convert from string # pass #tracker.set_location(r.record.location_id, timestmp=timestmp) tracker.set_location(r.record.location_id) response.confirmation = T("Checked-Out successfully!") response.view = "check-in.html" output = dict( form=form, title=title, ) return output # @ToDo: JSON representation for check-out from mobile devices else: raise HTTP(415, current.ERROR.BAD_FORMAT)
def apply_method(r, **attr): """ Apply method. @param r: the S3Request @param attr: controller options for this request """ if r.representation == "html": T = current.T s3db = current.s3db response = current.response table = r.table tracker = S3Trackable(table, record_id=r.id) title = T("Check-In") get_vars = r.get_vars # Are we being passed a location_id? location_id = get_vars.get("location_id", None) if not location_id: # Are we being passed a lat and lon? lat = get_vars.get("lat", None) if lat is not None: lon = get_vars.get("lon", None) if lon is not None: form_vars = Storage( lat=float(lat), lon=float(lon), ) form = Storage(vars=form_vars) s3db.gis_location_onvalidation(form) location_id = s3db.gis_location.insert(**form_vars) form = None if not location_id: # Give the user a form to check-in # Test the formstyle formstyle = current.deployment_settings.get_ui_formstyle() row = formstyle("test", "test", "test", "test") if isinstance(row, tuple): # Formstyle with separate row for label (e.g. default Eden formstyle) tuple_rows = True else: # Formstyle with just a single row (e.g. Bootstrap, Foundation or DRRPP) tuple_rows = False form_rows = [] comment = "" _id = "location_id" label = LABEL("%s:" % T("Location")) from .s3widgets import S3LocationSelector field = table.location_id #value = tracker.get_location(_fields=["id"], # as_rows=True).first().id value = None # We always want to create a new Location, not update the existing one widget = S3LocationSelector(show_latlon=True)(field, value) row = formstyle("%s__row" % _id, label, widget, comment) if tuple_rows: form_rows.append(row[0]) form_rows.append(row[1]) else: form_rows.append(row) _id = "submit" label = "" widget = INPUT(_type="submit", _value=T("Check-In")) row = formstyle("%s__row" % _id, label, widget, comment) if tuple_rows: form_rows.append(row[0]) form_rows.append(row[1]) else: form_rows.append(row) if tuple_rows: # Assume TRs form = FORM(TABLE(*form_rows)) else: form = FORM(*form_rows) if form.accepts(current.request.vars, current.session): location_id = form.vars.get("location_id", None) if location_id: # We're not Checking-in in S3Track terms (that's about interlocking with another object) #tracker.check_in() #timestmp = form.vars.get("timestmp", None) #if timestmp: # # @ToDo: Convert from string # pass #tracker.set_location(location_id, timestmp=timestmp) tracker.set_location(location_id) response.confirmation = T("Checked-In successfully!") response.view = "check-in.html" output = dict( form=form, title=title, ) return output # @ToDo: JSON representation for check-in from mobile devices else: raise HTTP(415, current.ERROR.BAD_FORMAT)
def merge(self, r, **attr): """ Merge form for two records @param r: the S3Request @param **attr: the controller attributes for the request @note: this method can always only be POSTed, and requires both "selected" and "mode" in post_vars, as well as the duplicate bookmarks list in session.s3 """ T = current.T session = current.session response = current.response output = {} tablename = self.tablename # Get the duplicate bookmarks s3 = session.s3 DEDUPLICATE = self.DEDUPLICATE if DEDUPLICATE in s3: bookmarks = s3[DEDUPLICATE] if tablename in bookmarks: record_ids = bookmarks[tablename] # Process the post variables post_vars = r.post_vars mode = post_vars.get("mode") selected = post_vars.get("selected", "") selected = selected.split(",") if mode == "Inclusive": ids = selected elif mode == "Exclusive": ids = [i for i in record_ids if i not in selected] else: # Error ids = [] if len(ids) != 2: r.error(501, T("Please select exactly two records"), next=r.url(id=0, vars={})) # Get the selected records table = self.table query = (table._id == ids[0]) | (table._id == ids[1]) orderby = table.created_on if "created_on" in table else None rows = current.db(query).select(orderby=orderby, limitby=(0, 2)) if len(rows) != 2: r.error(404, current.ERROR.BAD_RECORD, next=r.url(id=0, vars={})) original = rows[0] duplicate = rows[1] # Prepare form construction formfields = [f for f in table if f.readable or f.writable] ORIGINAL, DUPLICATE, KEEP = self.ORIGINAL, self.DUPLICATE, self.KEEP keep_o = KEEP.o in post_vars and post_vars[KEEP.o] keep_d = KEEP.d in post_vars and post_vars[KEEP.d] trs = [] init_requires = self.init_requires index = 1 num_fields = len(formfields) for f in formfields: # Render the widgets oid = "%s_%s" % (ORIGINAL, f.name) did = "%s_%s" % (DUPLICATE, f.name) sid = "swap_%s" % f.name init_requires(f, original[f], duplicate[f]) if keep_o or not any((keep_o, keep_d)): owidget = self.widget(f, original[f], _name=oid, _id=oid, _tabindex=index) else: try: owidget = s3_represent_value(f, value=original[f]) except: owidget = s3_str(original[f]) if keep_d or not any((keep_o, keep_d)): dwidget = self.widget(f, duplicate[f], _name=did, _id=did) else: try: dwidget = s3_represent_value(f, value=duplicate[f]) except: dwidget = s3_str(duplicate[f]) # Swap button if not any((keep_o, keep_d)): swap = INPUT( _value="<-->", _class="swap-button", _id=sid, _type="button", _tabindex=index + num_fields, ) else: swap = DIV(_class="swap-button") if owidget is None or dwidget is None: continue # Render label row label = f.label trs.append( TR(TD(label, _class="w2p_fl"), TD(), TD(label, _class="w2p_fl"))) # Append widget row trs.append( TR(TD(owidget, _class="mwidget"), TD(swap), TD(dwidget, _class="mwidget"))) index = index + 1 # Show created_on/created_by for each record if "created_on" in table: original_date = original.created_on duplicate_date = duplicate.created_on if "created_by" in table: represent = table.created_by.represent original_author = represent(original.created_by) duplicate_author = represent(duplicate.created_by) created = T("Created on %s by %s") original_created = created % (original_date, original_author) duplicate_created = created % (duplicate_date, duplicate_author) else: created = T("Created on %s") original_created = created % original_date duplicate_created = created % duplicate_date else: original_created = "" duplicate_created = "" # Page title and subtitle output["title"] = T("Merge records") #output["subtitle"] = self.crud_string(tablename, "title_list") # Submit buttons if keep_o or not any((keep_o, keep_d)): submit_original = INPUT( _value=T("Keep Original"), _type="submit", _name=KEEP.o, _id=KEEP.o, ) else: submit_original = "" if keep_d or not any((keep_o, keep_d)): submit_duplicate = INPUT( _value=T("Keep Duplicate"), _type="submit", _name=KEEP.d, _id=KEEP.d, ) else: submit_duplicate = "" # Build the form form = FORM( TABLE( THEAD( TR( TH(H3(T("Original"))), TH(), TH(H3(T("Duplicate"))), ), TR( TD(original_created), TD(), TD(duplicate_created), _class="authorinfo", ), ), TBODY(trs), TFOOT(TR( TD(submit_original), TD(), TD(submit_duplicate), ), ), ), # Append mode and selected - required to get back here! hidden={ "mode": "Inclusive", "selected": ",".join(ids), }) output["form"] = form # Add RESET and CANCEL options output["reset"] = FORM( INPUT( _value=T("Reset"), _type="submit", _name="reset", _id="form-reset", ), A(T("Cancel"), _href=r.url(id=0, vars={}), _class="action-lnk"), hidden={ "mode": mode, "selected": ",".join(ids), }, ) # Process the merge form formname = "merge_%s_%s_%s" % (tablename, original[table._id], duplicate[table._id]) if form.accepts( post_vars, session, formname=formname, onvalidation=lambda form: self.onvalidation(tablename, form), keepvalues=False, hideerror=False): s3db = current.s3db if form.vars[KEEP.d]: prefix = "%s_" % DUPLICATE original, duplicate = duplicate, original else: prefix = "%s_" % ORIGINAL data = Storage() for key in form.vars: if key.startswith(prefix): fname = key.split("_", 1)[1] data[fname] = form.vars[key] search = False resource = s3db.resource(tablename) try: resource.merge(original[table._id], duplicate[table._id], update=data) except current.auth.permission.error: r.unauthorised() except KeyError: r.error(404, current.ERROR.BAD_RECORD) except Exception: import sys r.error(424, T("Could not merge records. (Internal Error: %s)") % sys.exc_info()[1], next=r.url()) else: # Cleanup bookmark list if mode == "Inclusive": bookmarks[tablename] = [ i for i in record_ids if i not in ids ] if not bookmarks[tablename]: del bookmarks[tablename] search = True elif mode == "Exclusive": bookmarks[tablename].extend(ids) if not selected: search = True # Confirmation message # @todo: Having the link to the merged record in the confirmation # message would be nice, but it's currently not clickable there :/ #result = A(T("Open the merged record"), #_href=r.url(method="read", #id=original[table._id], #vars={})) response.confirmation = T("Records merged successfully.") # Go back to bookmark list if search: self.next = r.url(method="", id=0, vars={}) else: self.next = r.url(id=0, vars={}) # View response.view = self._view(r, "merge.html") return output
def widget( cls, r, record_ids=None, _class="action-lnk", ): """ Render an action item (link or button) to anonymize the provided records @param r: the S3Request @param record_ids: The list of record_ids to act on @param _class: HTML class for the action item @returns: the action item (a HTML helper instance), or an empty string if no anonymize-rules are configured for the target table, no target record was specified or the user is not permitted to anonymize it """ T = current.T default = "" # Determine target table if r.component: resource = r.component if resource.link and not r.actuate_link(): resource = resource.link else: resource = r.resource table = resource.table # Determine target record if not record_ids: return default # Check if target is configured for anonymize rules = resource.get_config("anonymize") if not rules: return default if not isinstance(rules, (tuple, list)): # Single rule rules["name"] = "default" rules = [rules] # Determine widget ID widget_id = "%s-anonymize" % table # Dialog and Form INFO = T( "The following information will be deleted from all the selected records" ) CONFIRM = T("Are you sure you want to delete the selected details?") #SUCCESS = T("Action successful - please wait...") form = FORM( P("%s:" % INFO), cls.selector(rules), P(CONFIRM), DIV( INPUT( value="anonymize_confirm", _name="anonymize_confirm", _type="checkbox", ), LABEL(T("Yes, delete the selected details")), _class="anonymize-confirm", ), DIV( INPUT( _class="small alert button anonymize-submit", _disabled="disabled", _type="submit", _value=T("Anonymize"), ), _class="anonymize-buttons", ), _class="anonymize-form", # Store action key in form hidden={"action-key": cls.action_key(widget_id)}, ) script = '''var submitButton=$('.anonymize-submit'); $('input[name="anonymize_confirm"]').off('.anonymize').on('click.anonymize',function(){if ($(this).prop('checked')){submitButton.prop('disabled',false);}else{submitButton.prop('disabled',true);}});''' current.response.s3.jquery_ready.append(script) return form
def widget( cls, r, label="Anonymize", ajaxURL=None, _class="action-lnk", ): """ Render an action item (link or button) to anonymize the target record of an S3Request, which can be embedded in the record view @param r: the S3Request @param label: The label for the action item @param ajaxURL: The URL for the AJAX request @param _class: HTML class for the action item @returns: the action item (a HTML helper instance), or an empty string if no anonymize-rules are configured for the target table, no target record was specified or the user is not permitted to anonymize it """ T = current.T default = "" # Determine target table if r.component: resource = r.component if resource.link and not r.actuate_link(): resource = resource.link else: resource = r.resource table = resource.table # Determine target record record_id = S3Anonymize._record_id(r) if not record_id: return default # Check if target is configured for anonymize rules = resource.get_config("anonymize") if not rules: return default if not isinstance(rules, (tuple, list)): # Single rule rules["name"] = "default" rules = [rules] # Check permissions to anonymize if not S3Anonymize.permitted(table, record_id): return default # Determine widget ID widget_id = "%s-%s-anonymize" % (table, record_id) # Inject script if ajaxURL is None: ajaxURL = r.url( method="anonymize", representation="json", ) script_options = { "ajaxURL": ajaxURL, } next_url = resource.get_config("anonymize_next") if next_url: script_options["nextURL"] = next_url cls.inject_script(widget_id, script_options) # Action button translated_label = T(label) action_button = A(translated_label, _class="anonymize-btn") if _class: action_button.add_class(_class) # Dialog and Form INFO = T("The following information will be deleted from the record") CONFIRM = T("Are you sure you want to delete the selected details?") SUCCESS = T("Action successful - please wait...") form = FORM( P("%s:" % INFO), cls.selector(rules), P(CONFIRM), DIV( INPUT( value="anonymize_confirm", _name="anonymize_confirm", _type="checkbox", ), LABEL(T("Yes, delete the selected details")), _class="anonymize-confirm", ), cls.buttons(), _class="anonymize-form", # Store action key in form hidden={"action-key": cls.action_key(widget_id)}, ) dialog = DIV( form, DIV( P(SUCCESS), _class="hide anonymize-success", ), _class="anonymize-dialog hide", _title=translated_label, ) # Assemble widget widget = DIV( action_button, dialog, _class="s3-anonymize", _id=widget_id, ) return widget
def formatted(self, retry=False): """ Formatted version of this report @param retry: add retry-action for sending to CWA @returns: a FORM containing - the QR-code - human-readable report details - actions to download PDF, or retry sending to CWA """ T = current.T table = current.s3db.disease_case_diagnostics # Personal Details data_repr = TABLE() data = self.data if not any(k in data for k in ("fn", "ln", "dob")): data_repr.append( TR( TD(T("Person Tested")), TD(T("anonymous"), _class="cwa-data"), )) else: labels = { "fn": T("First Name"), "ln": T("Last Name"), "dob": T("Date of Birth"), } for k in ("ln", "fn", "dob"): value = data[k] if k == "dob": value = self.to_local_dtfmt(value) data_repr.append( TR( TD(labels.get(k)), TD(value, _class="cwa-data"), )) # Test Station, date and result field = table.site_id if field.represent: data_repr.append( TR( TD(field.label), TD( field.represent(self.site_id), _class="cwa-data", ), )) field = table.probe_date if field.represent: data_repr.append( TR( TD(field.label), TD( field.represent(self.probe_date), _class="cwa-data", ), )) field = table.result if field.represent: data_repr.append( TR( TD(field.label), TD( field.represent(self.result), _class="cwa-data", ), )) # Details details = DIV( H5(T("Details")), data_repr, _class="cwa-details", ) # QR Code title = T("Code for %(app)s") % CWA qrcode = DIV( s3_qrcode_represent(self.get_link(), show_value=False), DIV(title, _class="cwa-qrcode-title"), _class="cwa-qrcode", ) if retry: qrcode.add_class("hide") # Form buttons buttons = [ BUTTON( T("Download PDF"), _class="tiny primary button cwa-pdf", _type="button", ), ] if retry: buttons[0].add_class("hide") buttons.append( BUTTON( T("Retry sending to %(app)s") % CWA, _class="tiny alert button cwa-retry", _type="button", )) # Generate form key formurl = URL( c="disease", f="case_diagnostics", args=[self.result_id], ) formkey = uuid.uuid4().hex # Store form key in session session = current.session keyname = "_formkey[testresult/%s]" % self.result_id session[keyname] = session.get(keyname, [])[-9:] + [formkey] form = FORM( DIV( DIV( details, qrcode, _class="small-12 columns", ), _class="row form-row", ), DIV( DIV( buttons, _class="small-12 columns", ), _class="row form-row", ), hidden={ "formurl": formurl, "cwadata": json.dumps(self.data), "_formkey": formkey, }, ) return form
def get_task_num_form(): form = FORM('Show:', INPUT(_name = 'task_num', _class='task_num', requires = IS_INT_IN_RANGE(1,101)), A(SPAN(_class='icon-refresh'), _onclick = 'tab_refresh();$(this).closest(\'form\').submit()', _href='#')) return form
def getGameFormBtn(game, user, gameStats): """ Gets a dictionary of form buttons that do stuff for the game page. Keyword Arguments: game -- row representing the current game user -- row representing the current user Return Values: formBtn -- dictionary of web2py forms -- 'start' Start Game button -- 'join' Join Game button -- 'leave' Leave Game button -- 'target' Target Eliminated button -- 'dead' I have been eliminated button """ from gluon import current, INPUT, FORM, redirect, URL, BUTTON db = current.db formBtn = { 'start': 'start', 'join': 'join', 'leave': 'leave', 'target': 'target', 'dead': 'dead' } if gameStats['players'] > 1: formBtn['start'] = FORM( INPUT( _type='submit', _value='(Host) Start Game', _class='btn btn-large btn-block btn-inverse abtn-large', _onclick= 'return confirm(\'Are you sure you want to start this game?\');' )) else: formBtn['start'] = BUTTON( '(Host) Start Game', _class='btn btn-large btn-block btn-inverse abtn-large', _onclick='alert(\'You need at least 2 players to start a game?\');' ) formBtn['join'] = FORM( INPUT(_type='submit', _value='Join Game', _class='btn btn-large btn-block btn-inverse abtn-large')) formBtn['leave'] = FORM( INPUT( _type='submit', _value='Leave Game', _class='btn btn-block abtn-small', _onclick= 'return confirm(\'Are you sure you want to leave this game?\');')) formBtn['target'] = FORM( INPUT(_type='submit', _value='Target Eliminated', _class='btn btn-large btn-block btn-inverse abtn-large')) formBtn['dead'] = FORM( INPUT( _type='submit', _value='I am dead.', _class='btn btn-block abtn-small', _onclick= 'return confirm(\'Are you sure you want to eliminate yourself?\');' )) if gameStats['players'] > 1 and formBtn['start'].process( formname='formBtnStart').accepted: startGameAssassins(game.id, user) redirect(URL('default', 'game', args=game.id)) if formBtn['join'].process(formname='formBtnJoin').accepted: joinGame(game.id, user) redirect(URL('default', 'game', args=game.id)) if formBtn['leave'].process(formname='formBtnLeave').accepted: leaveGame(game.id, user) redirect(URL('default', 'game', args=game.id)) if formBtn['target'].process(formname='formBtnTarget').accepted: killCompletedAssassins(game.id, user.id) redirect(URL('default', 'game', args=game.id)) if formBtn['dead'].process(formname='formBtnDead').accepted: query = db((db.player.game_id == game.id) & (db.player.player_id == user.id)).select(db.player.id)[0] killPlayer(game.id, user.id) #wasKilledAssassins() redirect(URL('default', 'game', args=game.id)) return formBtn
def getEditgamePlayers(game, user): """ Gets a list of players and buttons for the edit game page. Keyword Arguments: game -- row representing the current game user -- row representing the current user Return Values: out -- list containing dictionaries for each player -- 'name' string of the full name of the player -- 'status' string of the status of the player -- 'kill' '' or a button to kill the player -- 'kick' '' or a button to kick the player """ from gluon import current, INPUT, FORM, redirect, URL db = current.db #Rows for the current player's list players = db((db.player.player_id == db.auth_user.id) & (db.player.game_id == game.id)).select( db.player.status, db.player.id, db.player.player_id, db.auth_user.first_name, db.auth_user.last_name) out = [] for player in players: row = {'name': 'name', 'status': 'status', 'kill': '', 'kick': ''} action1 = 'Kill' action2 = 'Kick' if game.rules == 'Assassins': action1 = 'Eliminate' elif game.rules == 'Humans v. Zombies': action1 = 'Zombify' row['name'] = player.auth_user.first_name + ' ' + player.auth_user.last_name if game.host_id == player.player.player_id: row['name'] = row['name'] + ' (Host)' if game.game_status == "STARTED": row['status'] = player.player.status if row['status'] != 'DEAD' and game.game_status == 'STARTED': action = 'action' id = INPUT(_name='id', _type='text', _value=player.player.player_id, _class='hidden') kill = INPUT( _type='submit', _value=action1, _class='btn btn-mini', _onclick='return confirm(\'Are you sure you want to ' + action1.lower() + ' this player?\');') row['kill'] = FORM(id, kill) if row['kill'].process(formname='formBtnKill').accepted: player killPlayer(game.id, row['kill'].vars.id, user) redirect(URL('kiwi', 'editgame', args=game.id)) if player.player.player_id != user.id: id = INPUT(_name='id', _type='text', _value=player.player.id, _class='hidden') kick = INPUT( _type='submit', _value=action2, _class='btn btn-mini btn-danger', _onclick='return confirm(\'Are you sure you want to ' + action2.lower() + ' this player?\');') row['kick'] = FORM(id, kick) if row['kick'].process(formname='formBtnKick').accepted: kickPlayer(row['kick'].vars.id, user) redirect(URL('kiwi', 'editgame', args=game.id)) out.append(row) #End for player in players: #Sort players by status, then by name out.sort(key=lambda n: (n['status'], n['name'])) return out