[web2py] Re: comparing datetime objects in db query fails
Thanks for the solution. Sorry for the slow reply - I wanted to try it out, but haven't since I had already fixed the problem by explicitly converting from strings to datetimes, and moved on with my work. One question: Why isn't the use of PARSE_COLTYPES the default behavior? It seems DAL/sqlite doesn't do the right thing without it. thx, Luis.
[web2py] Re: in a db query, why the error: can't compare datetime.datetime to Field
Ah yes! Thank you, Greg! I come from the Matlab world and am not very experienced with object oriented program, but I was suspecting it was something like that. I think I found a true bug in the way datetime objects work in db queries, though -- I will post under a new subject heading. Thanks!!! Luis.
[web2py] comparing datetime objects in db query fails
Doing database queries on datetime.datetime fields seems broken. Here's an example: I have a database with a table 'transEntry' which includes a 'datetime' field: db.define_table('itemEntry', * Field('dateTime','datetime'),* Field('upc', 'string'), Field('description', 'string'), Field('storeNumber', 'integer'), Field('terminalNumber', 'integer'), Field('transactionNumber', 'integer'), Field('operatorNumber', 'integer'), Field('quantity', 'integer'), Field('price', 'double'), Field('action', 'integer'), Field('sequenceNumber', 'integer')) I do a search based on other fields, and it works fine: first_search = db((db.transEntry.storeNumber==store_num) (db.transEntry.terminalNumber==lane_num)).select(orderby=db.transEntry.dateTime) len(first_search) 5213 Let's look at one of the results: In [173]: ex = first_search[524].dateTime In [174]: ex Out[174]: datetime.datetime(2010, 12, 11, 17, 50, 55) Now try to find a subset of the original query, entries antecedent to ex : In [183]: broken_search = db( (db.transEntry.dateTime ex) (db.transEntry.storeNumber==store_num) (db.transEntry.terminalNumber==lane_num) ).select( orderby=db.transEntry.dateTime) In [184]: len(gar2) Out[184]: 270 ?? Why are there only 270, we were expecting 523 of them?? Let's take a closer look: In [186]: gar2[1].dateTime Out[186]: datetime.datetime(2010, 12, 10, 10, 55, 39) In [187]: gar2[2].dateTime Out[187]: datetime.datetime(2010, 12, 10, 10, 56, 19) In [189]: gar2[269].dateTime *Out[189]: datetime.datetime(2010, 12, 10, 22, 40, 26)* In [190]: ex Out[190]: datetime.datetime(*2010, 12, 11, 17, 50, 55*) ?? For some reason, the closest result found is almost 24 hours away from 'ex' ?? *?? Why didn't it find this one :* In [191]: *gar[523].dateTime* Out[191]: *datetime.datetime(2010, 12, 11, 17, 49, 37)* I can't understand what's happening! It seems that comparisons of datetime fields in db queries just don't work correctly? If anyone can explain/fix this, it will be much appreciated!! Thanks! Luis.
Re: [web2py] Re: comparing datetime objects in db query fails
Cut and paste, sorry! Wanted to rename broken_search for clarity and failed. Late night... —« sent from my Droid tablet »— On Aug 19, 2011 12:12 AM, Jose C houdinihoun...@gmail.com wrote: In [183]: broken_search = db( (db.transEntry.dateTime ex) (db.transEntry.storeNumber==store_num) (db.transEntry.terminalNumber==lane_num) ).select( orderby=db.transEntry.dateTime) In [184]: len(gar2) Out[184]: 270 In your exmaple above, in [183] you're assigning to variable `broken_search`. From there on you're working with the contents of variable `gar2`. Could that be your problem, or was it a cut and paste error?
[web2py] Re: comparing datetime objects in db query fails
Apologies again - all typos. The first query was built by typing (no longer in my ipython history), and full of mistakes. The proper way to do this is to create a simple sample that everyone can replicate (too tired late last night to do so..). Will do so now, constrained by work interruptions. Thanks, Luis.
[web2py] Re: comparing datetime objects in db query fails
I think you are right, Anthony! In the original query, first_search (or gar with), first_search[270] is the first entry on the new date!!! (and also first_search[269] is the same entry as broken_query[269], so the search results are the same up to that point). I will still make a simple example all can try, but I think Anthony is right -- it only checks the date, not the time! Luis.
[web2py] Re: comparing datetime objects in db query fails
Here is a simple example ... but it seems to behave properly: test datetime in db queries import sys sys.path.append(/mnt/data1/web2py) from gluon import * import datetime import random db = DAL('sqlite://debug_datetime.sqlite', folder='/home/goncalves/matlab/objrec/target_stacked_lanes', auto_import=True) db.define_table('magic', Field('DT', 'datetime'), Field('val', 'integer')) # Dec 12 2010, 12:30:45 init_date = datetime.datetime(2010, 12, 10, 12, 30, 45) cur_date = init_date cur_val = 0 for i in range(1000): db.magic.insert(DT = cur_date, val = cur_val) # we increment from 30 to 300 seconds at a time rand_int = random.randint(30, 300) delta = datetime.timedelta(0, rand_int) cur_date = cur_date + delta cur_val = cur_val + rand_int # make test date 24 hours later test_date = init_date + datetime.timedelta(1) results = db( db.magic.DT test_date).select( orderby=db.magic.DT ) print 'Initial date: ', init_date print 'Test date:', test_date print 'Last query result:', results[-1].DT print 'Next entry :', db.magic[len(results)+1].dT When run it produces: Initial date: 2010-12-10 12:30:45 Test date: 2010-12-11 12:30:45 Last query result: 2010-12-11 12:29:55 Next entry in DB : 2010-12-11 12:33:45 So it behaves perfectly fine. Something else is the problem in my application! Not sure what, though. I'm running python 2.7 on my desktop, 2.6.5 on laptop, and have the problem on both. Using webp2y version : Version 1.97.1 (2011-06-26 19:25:44) I am the only person accesssing the DB. The DB is 62MB. Could it be that using a field name of 'dateTime' is somehow confusing web2py? Thanks, Luis.
[web2py] Re: comparing datetime objects in db query fails
Ciao Massimo, I wasn't clear in my post : It's not a web app, I'm using DAL as part of a data analysis program I am writing. I debug with ipython, but the script/programs I write can be called like : python test_412_determine_open_or_closed_lane.py , which outputs results to a file. thx, Luis.
[web2py] Re: comparing datetime objects in db query fails
I think I have figured it out, with the help of a python expert at work. I am using sqlite3, which internally stores data as strings. When creating my real database (not the toy example), I read raw date and time data as an isoformat string, and relied on DAL/web2py to convert. But perhaps in sqlite the field was just stored as the isoformat string: db.recs.insert( , dateTime = isoformat_string, ... ) where 'dateTime' is a field of type 'datetime' If I look at a database row, dateTime is shown as a datetime object, and includes both the proper date and time, so presumably in reading the sqlite database web2py/DAL knows how to translate an isoformat to a datetime: In [12]: db.recs[110].dateTime Out[12]: datetime.datetime(2010, 12, 11, 16, 16, 36) The mismatch occurs when attempting to do a db query with datetime fields, because I think that web2py/DAL converts a datetime to a string with str() instead of datetime.isoformat(), and so when sqlite does the comparision, only the date matches, but not the time: In [7]: str(dt) Out[7]: '2010-12-11 16:34:34' In [8]: dt.isoformat() Out[8]: '2010-12-11T16:34:34' Before I had this all figured out, I had added a new field to my database, iso_str, of type 'string', and now I do all my date/time queries with that and it works fine. Presumably if I rebuilt my database so that I converted my isoformat date/time data to a datetime object before inserting into the DB, all would be fine too! Luis.
[web2py] in a db query, why the error: can't compare datetime.datetime to Field
Let my_DT = datetime.datetime( 2011, 08, 16) db.define_table( 'entry', Field('DT' = 'datetime' ) ) (and add data records to the database ...) In a db query, this works: db( db.entry.DT my_DT).select() but this does not: db( my_DT db.entry.DT).select() producing error : can't compare datetime.datetime to Field Why does that happen? Thanks, Luis.
[web2py] web2py ranked best out of Six web frameworks
There was an article that compares CubicWeb, Django, Pyramid, Web.py, Web2py, and Zope 2and it gave web2py the highest rankings! link: http://www.infoworld.com/d/application-development/pillars-python-six-python-web-frameworks-compared-169442 (Sorry if this is considered spam on the list -- but I found it to be great news that will help make web2py more popular!!) Luis.
[web2py] Re: web2py ranked best out of Six web frameworks
(oops, sorry, didn't see already posted).
[web2py] Re: SQLFORM with divs or ordered lists instead of tables (for easier control with CSS)
Yes ... too many :( Here's a 'simple' one: The database table definition, which I use as a form for input: db.define_table('scorecard', Field('offense1', db.player, requires=IS_IN_DB( db, 'player.id', '%(name)s', zero=T('choose one')) ), Field('defense1', db.player, requires=IS_IN_DB( db, 'player.id', '%(name)s', zero=T('choose one')) ), Field('offense2', db.player, requires=IS_IN_DB( db, 'player.id', '%(name)s', zero=T('choose one')) ), Field('defense2', db.player, requires=IS_IN_DB( db, 'player.id', '%(name)s', zero=T('choose one')) ), Field('fifth', db.player, requires=IS_IN_DB( db, 'player.id', '%(name)s', zero=T('choose one')) ), Field('score1', 'integer', requires=IS_IN_SET([1, 2, 3, 4, 5],zero=None)), Field('score2', 'integer', requires=IS_IN_SET([1, 2, 3, 4, 5],zero=None)), Field('start', 'datetime', readable=False, writable=False), Field('finish', 'datetime', readable=False, writable=False), Field('single', 'boolean', readable=False, writable=False)) # single game during round-robin rotate play, or part of a game-set-match I would like this to display something like: https://lh3.googleusercontent.com/-043w1FYNTj8/Tipod6h9_zI/HFk/0eX4V6S0Uf0/scorecard.png The input is a scorecard for a game. Two teams with two players each, and a fifth person that will play the next game. The user defines who is playing the current game, and who is sitting out. When the game is over, they select the scores. On 'submit', the teams and scores are recorded, and the form is shown again, with a suggested line-up for the next game (but the user can alter the line-up if he wants). In the controller: def rotate_5_man(): form = SQLFORM( db.scorecard ) # retrieve previous player positions. # pre-fill form with some suggestions if form.accepts( .. ) # record score, # figure out how to rotate players for next game return dict(form=form) In the view, rotate_5_man.html : {{extend 'layout.html'}} {{=form}} So right now, the display of the form is quite rudimentary (each item gets shown in order, listed vertically). Is there a simple way to get the above layout instead? Preferably done with minimal additional python/web2py/html, but via CSS instead! Thanks!!! Luis.
[web2py] Re: how to iterate efficiently (memory-wise) through a huge DAL query
Thanks, Massimo! Even if I grab 1000 at a time (which is definitely better to do!!), I still have to wait for minutes before I get rows back! However, I have found that this is 'fast' : n = db.table.count() # not sure if that's the syntax, but somehow find out how many records in table for i in range(1,n): row = db.table(i) # do something with r This works fine if I want to iterate through every single entry in the database (and I assume there are no breaks in the record.id values). I don't know how to do something equivalent when the query/set represents an arbitrary (large) number of table records. I even tried just extracting the record.id values, id_index = db(q).select( db.table.id, limitby=(1000,1) ) to then access them through db.table(i), row = db.table( id_index[i].id ) but just getting the id_index list of record.id's was slow! I'm using sqlite3, on linux, with 4GB of RAM, and the DB is about 700MB in size (830MB with some index tables built). Thanks!!! Luis.
[web2py] Re: how to iterate efficiently (memory-wise) through a huge DAL query
Thanks, Vineet! Lot's of good info there! I don't have actual code yet, because I couldn't even get the db queries to work in a reasonable amount of time. The little code I showed in my initial post already runs slow ( my DB records are db.itemEntry, not db.table ...). The slowness (so far) is due to doing a query/select on a very large DB. I need to figure out how to query/select more efficiently. I wonder if the problem is with sqlite3 itself, since it stores the entire DB in a single file. I have constructed index tables for the fields I am searching on, but it is still incredibly slow. (see post below in reply to Massimo too!). Thanks! Luis.
Re: [web2py] Re: SQLFORM with divs or ordered lists instead of tables (for easier control with CSS)
I am just a beginner with CSS/HTML, and so maybe I have a misconceived idea of what CSS can/should do and the right way to use it. Naively, I thought that I could use the #id=table-field entries in CSS to control placement/shape of the form elements, and not need to change much more in the controller or the view? It seems that if I have to use custom forms, then I might as well not even bother with using SQLFORM -- it's pretty much like building the form piece by piece in the view? thanks, Luis. On Fri, Jul 22, 2011 at 11:42 PM, Anthony abasta...@gmail.com wrote: What's wrong with this method - http://web2py.com/book/default/chapter/07#Custom-forms - you can put the form widgets wherever you want? Or specifically, how would better/smarter/proper use of the #id table-field entries help? What would you like to see in the rendered form HTML that would enable you to do what you want with just CSS? Anthony On Saturday, July 23, 2011 2:33:54 AM UTC-4, Luis Goncalves wrote: Yes ... too many :( Here's a 'simple' one: The database table definition, which I use as a form for input: db.define_table('scorecard', Field('offense1', db.player, requires=IS_IN_DB( db, 'player.id', '%(name)s', zero=T('choose one')) ), Field('defense1', db.player, requires=IS_IN_DB( db, 'player.id', '%(name)s', zero=T('choose one')) ), Field('offense2', db.player, requires=IS_IN_DB( db, 'player.id', '%(name)s', zero=T('choose one')) ), Field('defense2', db.player, requires=IS_IN_DB( db, 'player.id', '%(name)s', zero=T('choose one')) ), Field('fifth', db.player, requires=IS_IN_DB( db, 'player.id', '%(name)s', zero=T('choose one')) ), Field('score1', 'integer', requires=IS_IN_SET([1, 2, 3, 4, 5],zero=None)), Field('score2', 'integer', requires=IS_IN_SET([1, 2, 3, 4, 5],zero=None)), Field('start', 'datetime', readable=False, writable=False), Field('finish', 'datetime', readable=False, writable=False), Field('single', 'boolean', readable=False, writable=False)) # single game during round-robin rotate play, or part of a game-set-match I would like this to display something like: https://lh3.googleusercontent.com/-043w1FYNTj8/Tipod6h9_zI/HFk/0eX4V6S0Uf0/scorecard.png The input is a scorecard for a game. Two teams with two players each, and a fifth person that will play the next game. The user defines who is playing the current game, and who is sitting out. When the game is over, they select the scores. On 'submit', the teams and scores are recorded, and the form is shown again, with a suggested line-up for the next game (but the user can alter the line-up if he wants). In the controller: def rotate_5_man(): form = SQLFORM( db.scorecard ) # retrieve previous player positions. # pre-fill form with some suggestions if form.accepts( .. ) # record score, # figure out how to rotate players for next game return dict(form=form) In the view, rotate_5_man.html : {{extend 'layout.html'}} {{=form}} So right now, the display of the form is quite rudimentary (each item gets shown in order, listed vertically). Is there a simple way to get the above layout instead? Preferably done with minimal additional python/web2py/html, but via CSS instead! Thanks!!! Luis.
[web2py] Re: SQLFORM with divs or ordered lists instead of tables (for easier control with CSS)
Thanks, Anthony! I still haven't figured it out completely (mostly because I don't know very much about CSS and someone else is dealing with that part of the project). Thanks! Luis.
[web2py] how to iterate efficiently (memory-wise) through a huge DAL query
I am trying to use web2py's DAL for a project that is not a webapp. I have a database with about 8M entries, and I want to process the data. Suppose I create a query that returns a lot of results: extreme case example: q = db.table.id0 How do I iterate through all the results of a large query, q, *without*having to retrieve all the data to memory? Is there something better than: # q = a db query that returns a huge number of results n = q.count() s = db(q) for i in range(1,n): r = s.select( limitby=(i,1)).first() # do something with r ... I've tried this out (interactively, to see what is happening), and when I get to i=2, s.select( limitby=(2,1)).first() the computer starts to swap and hangs for minutes. So my question, again, is: Is there an efficient way to iterate through a large query (or set = db(query) ) that avoids overloading the system memory? Thanks, Luis.
[web2py] Re: proper way to mobile and desktop 'skins'
I've been away to conferences and somehow missed these replies! Thank you all for the replies! I send the same content, so in principle CSS definitions should be able to restyle satisfactorily. I actually found two books that seem quite helpful: by Jonathan Stark, published by O'Reilly, Building iPhone apps with HTML, CSS, and JavaScript without ObjectiveC or Cocoa, and Building Android apps with HTML, CSS, and JavaScript. The two books are very similar, and they describe a way to create native apps by way of creating a webapp and using PhoneGap. (We are happy enough just having a web app that looks good!!!). Thanks!! L.
[web2py] SQLFORM with divs or ordered lists instead of tables (for easier control with CSS)
Tables are hard to control in CSS, is there a way to have SQLFORM use divs or lists instead? I have seen many(!) posts about redefining SQLFORM and making it more flexible, but I'm not sure if any conclusion has been reached. Thanks, Luis.
[web2py] Re: How to temporarily redirect all requests
Hello Anthony, and others! I implemented your very first suggestion, code in a model, outside of a function, as you (and pbreit) suggested. It worked fine! It's been very hectic (meetings/travel) and I haven't had a chance to reply until now. Thanks for your help (everybody!) !!! Luis.
[web2py] Re: how to use contrib/login_methods/linkedin_account.py
I didn't. But by doing the authentication manually (that is, in an interactive shell), I was able to connect to linked in. I realized that I wouldn't be able to get the information that I wanted though (email address - never provided by linkedin!), so I gave up. But the web2py linked-in auth is broken, as far as I can tell. The same thing with facebook. I think there are some steps that are just missing in the web2py implementation. I have a simple script that works with facebook auth (I can get all the info from a person and their graph on facebook) -- but I don't know how to integrate that with the web2py auth. If you, or anyone else, wants my facebook login script, I can post it. Luis.
[web2py] How to temporarily redirect all requests
Hello Everyone! Is there a simple/efficient/secure way to temporarily redirect all requests to a specific page? (all requests except for those that define a few actions that are permitted at that point in time) The context: - When user logs in, he needs to choose the version of the website to use (different version access different sets of data) - Until he chooses a version, clicking on any of the menu options, or links, or typing in any URL should not execute normally, but rather send him (keep him on) a page that tells him to please select a version - Ideally, selecting the version is done from the 'version' menubar option, so these still have to work properly. An ugly way to do this is to have every single possible action (URL,controller) check if the version selection has been done or not, but that seems like an inelegant, brute-force approach (and prone to errors if new functionality is added whilst forgetting to include the check). Thanks!!! Luis.
[web2py] Re: How to temporarily redirect all requests
more thoughts: could I do something like: - define a shared global variable session.version - = -1 initially, signifying no choice made - ? use a callback that gets executed *before *the controller that responds to the request - if session.version -1: let the responding controller do its thing else: if controller allowed to run: let the controller run else: redirect to 'please choose version' Is it possible to implement such a callback??? (or is this not the right/best way to achieve the functionality I need?) thanks, Luis.
[web2py] Re: How to temporarily redirect all requests
Awesome!!! Thanks!!! I will try it out!!! Luis.
[web2py] can a login_onaccept callback open another view?
Hello!! As part of the login process, I need the user to make a choice (select one of the multiple versions of the site he has access to, for example), before being redirected to whatever _login_next is. Is it possible for a login_onaccept callback to present a view with a form? My naive approach does not seem to work. What is the proper way to augment the login process with user interaction? Thanks!!! Luis. Here is the barebones code, to illustrate what I am trying to do: def user_choice(form_login): form = SQLFORM.factory( Field('choices', requires=IS_IN_SET(['a','b','c']))) if form.accepts( request.vars, session ): session.flash='It works!' redirect(auth.settings.login_next) return dict(form=form) auth.settings.login_onaccept = user_choice # views/default/user_choice.html {{=form}}
Re: [web2py] Re: Temporary changing default values of a Form
Done! Thank you!!! Luis. On Thu, Jul 7, 2011 at 6:24 PM, Massimo Di Pierro massimo.dipie...@gmail.com wrote: Please open a ticket in google code. If this is a web2py but will fix asap. On Jul 6, 11:24 pm, Luis Goncalves lgoncal...@gmail.com wrote: In fact, just to make sure there wasn't something hidden in my app affecting the behavior, I downloaded a fresh install of web2py, and get the same error: File /home/pierluigi/web2py/gluon/tools.py, line 1796, in register user = self.db(table_user[username] == form.vars[username]).select().first() KeyError: 'email' Adding just this code to the 'welcome' app: def user(): if request.args(0)=='register': auth.settings.table_user.email.default = ' l...@vision.caltech.edu' auth.settings.table_user.email.writable=False auth.settings.registration_requires_verification = False return dict(form=auth()) L. On Wed, Jul 6, 2011 at 8:35 PM, Luis Goncalves lgoncal...@gmail.com wrote: Yes, when I click on the invite and go to the website I get the registration form filled out with email (and name (excluded from my shortened example)) visible and non-editable. Luis. —«sent by mobile»— On Jul 6, 2011 8:17 PM, Massimo Di Pierro massimo.dipie...@gmail.com wrote: Are you sure your db.registrant has an email? On Jul 6, 10:04 pm, Luis Goncalves lgoncal...@gmail.com wrote: I still get the same error: File /home/ubuntu/web2py/gluon/tools.py, line 1683, in register user = self.db(table_user[username] == form.vars[username]).select().first() KeyError: 'email' I don't know if it makes a difference or not, but I'm using emails for login (not a username) -- as is probably clear to you from the above error. Code is now: def user(): if request.args(0)=='register': registrant = db( db.registrant.token == request.vars.token ).select().first() auth.settings.table_user.email.default = registrant.email auth.settings.table_user.email.writable=False auth.settings.registration_requires_verification = False return dict(form=auth())
Re: [web2py] Temporary changing default values of a Form
I found the answer searching through the group posts: form.element(_name='email')['_readonly']=True although this doesn't seem to be documented in the manual, and even looking through the gluon directory (and grepping for _readonly ) didn't reveal anything. Would this have been obvious to someone more proficient with web2py (I've only been using it for about a month)? thx! Luis.
Re: [web2py] How to call user/register with pre-defined fields (name, email)?
For the record, here's how I was able to implement an by invitation only registration form. Assuming that the user received an email with a link of form http://.../default/user/register?token=sfaasdfasfa, and assuming I have defined a db table 'registrant' associating a token with a name and email, here's the bare-bones functionality, where the user sees a registration form with his name and email pre-filled out (and not editable), and he can pick a password. Note that to get web2py's Auth() class to do it's registration things (use all the settings to encrypt passwords, insert new user in database, send email verification email, etc), this has to be done at http:///user/register def user(): if request.args(0)=='register': form=auth.register() registrant = db( db.registrant.token == request.vars.token ).select().first() form.element(_name='first_name').update(_value=registrant.first_name) form.element(_name='last_name').update(_value=registrant.last_name) form.element(_name='email').update(_value=registrant.email) form.element(_name='first_name')['_readonly']=True form.element(_name='last_name')['_readonly']=True form.element(_name='email')['_readonly']=True return dict(form=form) Quite short and sweet, once you figure it out :) Thanks for everybody's help!!! L.
[web2py] easy way to validate a list of emails?
Hello!!! I have a form where an organizer can input a list of comma-separated email address, so that each person receives an invitation to register on the website (you can only register for the site if you have an invitation). Is there an easy way to get the if form.accepts() to use requires=IS_EMAIL() when the form element is not just a single email address, but a list of comma-separated email addresses? Thanks! Luis.
Re: [web2py] easy way to validate a list of emails?
Excellent! Works perfectly!! Also a great lesson in how to extend the set of web2py form validators! Thank you, Bruno!!! Obrigado!!! Luis.
[web2py] Re: Temporary changing default values of a Form
Good point! Unfortunately, I am not expert enough to understand how to do this in my case, because I am using the form=auth.register(). Wouldn't I have to do what you suggest inside Auth.register ? (for an explanation of why I am doing this, see: https://groups.google.com/forum/#!topic/web2py/O3O6J5FgXjU ) def user(): if request.args(0)=='register': db.table_user.email.writable=False # gives error form=auth.register() registrant = db( db.registrant.token == request.vars.token ).select().first() form.element(_name='email').update(_value=registrant.email) form.element(_name='email')['_readonly']=True return dict(form=form) Thanks!! Luis.
[web2py] Re: Temporary changing default values of a Form
Both with Massimo's auth.settings.table_user.email.default = registrant.email auth.settings.table_user.email.writable=False form=auth.register() and with your db[auth.settings.table_user_name].email.writable=False db[auth.settings.table_user_name].email.default=registrant.email form=auth.register() I get the error Exception: Target receiver address not specified at the line ofform=auth.register() For reference, the entire block (with error handling removed for clarity) is: def user(): if request.args(0)=='register': registrant = db( db.registrant.token == request.vars.token ).select().first() db[auth.settings.table_user_name].email.writable=False db[auth.settings.table_user_name].email.default=registrant.email form=auth.register() return dict(form=form) return dict(form=auth())
[web2py] Re: Temporary changing default values of a Form
Actually, I still want email verification to happen (because someone else may stumble upon the link and register with a password unknown to the real user). Nevertheless, I disabled registration verification, and now I get an error deep within gloun/tools.py Error occurs after entering password and submitting the form. (same error with your and Massimo's version of the solution): File /home/ubuntu/web2py/gluon/tools.py, line 1683, in register user = self.db(table_user[username] == form.vars[username]).select().first() KeyError: 'email' Maybe making table_user.email.writable=False prevents auth.register() from creating a new table entry for the new user??? Again, for reference, the (essential) code: def user(): if request.args(0)=='register': registrant = db( db.registrant.token == request.vars.token ).select().first() auth.settings.registration_requires_verification = False db[auth.settings.table_user_name].email.writable=False db[auth.settings.table_user_name].email.default=registrant.email # this causes same error # auth.settings.table_user.email.default = registrant.email # auth.settings.table_user.email.writable=False form=auth.register() return dict(form=form) return dict(form=auth())
[web2py] Re: Temporary changing default values of a Form
I still get the same error: File /home/ubuntu/web2py/gluon/tools.py, line 1683, in register user = self.db(table_user[username] == form.vars[username]).select().first() KeyError: 'email' I don't know if it makes a difference or not, but I'm using emails for login (not a username) -- as is probably clear to you from the above error. Code is now: def user(): if request.args(0)=='register': registrant = db( db.registrant.token == request.vars.token ).select().first() auth.settings.table_user.email.default = registrant.email auth.settings.table_user.email.writable=False auth.settings.registration_requires_verification = False return dict(form=auth())
Re: [web2py] Re: Temporary changing default values of a Form
Yes, when I click on the invite and go to the website I get the registration form filled out with email (and name (excluded from my shortened example)) visible and non-editable. Luis. —«sent by mobile»— On Jul 6, 2011 8:17 PM, Massimo Di Pierro massimo.dipie...@gmail.com wrote: Are you sure your db.registrant has an email? On Jul 6, 10:04 pm, Luis Goncalves lgoncal...@gmail.com wrote: I still get the same error: File /home/ubuntu/web2py/gluon/tools.py, line 1683, in register user = self.db(table_user[username] == form.vars[username]).select().first() KeyError: 'email' I don't know if it makes a difference or not, but I'm using emails for login (not a username) -- as is probably clear to you from the above error. Code is now: def user(): if request.args(0)=='register': registrant = db( db.registrant.token == request.vars.token ).select().first() auth.settings.table_user.email.default = registrant.email auth.settings.table_user.email.writable=False auth.settings.registration_requires_verification = False return dict(form=auth())
Re: [web2py] Re: Temporary changing default values of a Form
In fact, just to make sure there wasn't something hidden in my app affecting the behavior, I downloaded a fresh install of web2py, and get the same error: File /home/pierluigi/web2py/gluon/tools.py, line 1796, in register user = self.db(table_user[username] == form.vars[username]).select().first() KeyError: 'email' Adding just this code to the 'welcome' app: def user(): if request.args(0)=='register': auth.settings.table_user.email.default = 'l...@vision.caltech.edu' auth.settings.table_user.email.writable=False auth.settings.registration_requires_verification = False return dict(form=auth()) L. On Wed, Jul 6, 2011 at 8:35 PM, Luis Goncalves lgoncal...@gmail.com wrote: Yes, when I click on the invite and go to the website I get the registration form filled out with email (and name (excluded from my shortened example)) visible and non-editable. Luis. —«sent by mobile»— On Jul 6, 2011 8:17 PM, Massimo Di Pierro massimo.dipie...@gmail.com wrote: Are you sure your db.registrant has an email? On Jul 6, 10:04 pm, Luis Goncalves lgoncal...@gmail.com wrote: I still get the same error: File /home/ubuntu/web2py/gluon/tools.py, line 1683, in register user = self.db(table_user[username] == form.vars[username]).select().first() KeyError: 'email' I don't know if it makes a difference or not, but I'm using emails for login (not a username) -- as is probably clear to you from the above error. Code is now: def user(): if request.args(0)=='register': registrant = db( db.registrant.token == request.vars.token ).select().first() auth.settings.table_user.email.default = registrant.email auth.settings.table_user.email.writable=False auth.settings.registration_requires_verification = False return dict(form=auth())
Re: [web2py] Temporary changing default values of a Form
This doesn't seem to work with auth() forms: form = auth.register() form.vars.email = 'l...@vision.caltech.edu' return dict(form=form) doesn't show the predefined value for 'email' in a view that renders {{=form}} Does anybody know why? Thanks!! Luis.
Re: [web2py] Re: Temporary changing default values of a Form
Yes, I am trying to create an 'invitation' only registration, where the person receives an email with a link (and identifying token), and on my website I use the token to pre-populate the registration form, so that the user only has to pick his password. thx, Luis. On Tue, Jul 5, 2011 at 10:20 AM, Massimo Di Pierro massimo.dipie...@gmail.com wrote: Can you explain the logic? Are you trying to override whatever emails is typed in by the user on registration? On Jul 5, 12:08 pm, Luis Goncalves lgoncal...@gmail.com wrote: This doesn't seem to work with auth() forms: form = auth.register() form.vars.email = 'l...@vision.caltech.edu' return dict(form=form) doesn't show the predefined value for 'email' in a view that renders {{=form}} Does anybody know why? Thanks!! Luis.
Re: [web2py] Temporary changing default values of a Form
That worked great!!! Thanks so much, Anthony!!! L. On Tue, Jul 5, 2011 at 10:23 AM, Anthony abasta...@gmail.com wrote: I'm not sure you can pre-populate a registration form that way. form.vars.email has to be set after the form is created but before form.accepts is called -- however, auth.register() creates the form and calls form.accepts. Instead, you can pre-populate by manipulating the form DOM directly: form.element(_name='email').update(_value='lu...@vision.caltech.edu') Anthony On Tuesday, July 5, 2011 1:08:31 PM UTC-4, Luis Goncalves wrote: This doesn't seem to work with auth() forms: form = auth.register() form.vars.email = 'lu...@vision.caltech.edu' return dict(form=form) doesn't show the predefined value for 'email' in a view that renders {{=form}} Does anybody know why? Thanks!! Luis.
Re: [web2py] Temporary changing default values of a Form
One more question: How do I make the pre-populated elements of the form appear read-only (so that they cannot be altered)? I've tried in the view: {{=form.custom.begin}} divFirst name: {{=predef.fname}}/div divLast name: {{=predef.lname}}/div divEmail: {{=predef.email}}/div divPassword: {{=form.custom.widget.password}}/div divVerify password: {{=form.custom.widget.password_two}}/div {{=form.custom.submit}} {{=form.custom.end}} but then the elements for which I don't use the widget (to avoid being edited), seem not to be passed with the submit ( the auth.register method did not accept the form as complete ) is there some way to set an element of a form to be read-only? Thanks again! Luis.
[web2py] why doesn't INPUT _type='checkbox' return values of True or False, instead of 'on' or None?
Hello! It seems to me that the behavior of checkboxes is different and non-standard from the rest of input types, causing one to handle it as a special case (when trying to automate input field processing). In my application, an admin can create profile forms through a friendly interface. These forms can include string, text, checkbox, and lists (sets). A user of the system can see his current profile (rendered by generating a form given a definition of the form elements stored in a database), and edit it. The editing is very clean and straightforward: for field in event_fields: value = form.vars[str(field.id)] if value: # check if entry already exists and update, otherwise create prev_entry = db( (db.event_profile_entry.person == me.id) (db.event_profile_entry.event == session.cur_event) (db.event_profile_entry.event_profile_field == field.id) ).select().first() if prev_entry: prev_entry.update_record( data = value ) else: db.event_profile_entry.insert( person = me.id, event = session.cur_event, event_profile_field = field.id, data = value ) EXCEPT that a checkbox either has a value = 'on' or = None. If checkbox returned values of True or False, the code would work fine for checkboxes too, but as it is now, they will require special code. Is it worth changing the behavior of checkbox to be more like the rest of the input types? Thanks, Luis.
Re: [web2py] how to implement database tables with one level of indirection?
Hello Richard! I looked at this, but wasn't sure how it could help -- what I need is a way for a (non-technical) admin to create profile forms with arbitrary fields (through a friendly web interface), and then users to be able to view and edit their (run-time reconfigurable) profiles. At any rate, the method I described above seems to work quite well, thanks to web2py's versatility, allowing me to define forms programmatically (excerpt below). I was wondering if there was a more clever/efficient/proper way to do so. Perhaps not! Thanks!! Luis. for field in event_fields: # see if person has a pre-defined value found = False for my_efield in me.event_field: if my_efield.display_title == field.display_title: found = True break if found: if field.data_type == 'string': new_input = INPUT(_type = field.data_type, _name = field.id, requires=IS_NOT_EMPTY(), _value=my_efield.data ) form[0].insert(-2, TR(field.display_title+':', new_input )) elif field.data_type == 'text': . else: if field.data_type == 'string': new_input = INPUT(_type = field.data_type, _name = field.id, requires=IS_NOT_EMPTY()) form[0].insert(-2, TR(field.display_title+':', new_input )) elif field.data_type == 'text':
Re: [web2py] how to implement database tables with one level of indirection?
Thanks for the links!! Django dynamic formsets seems powerful! When I first started off, I investigated using django, but found it very difficult. Web2py is so much easier to use (especially with the clear manual, and one click install with working apps ('Welcome'))!!! Maybe I'll end up contributing a friendly dynamic form creator for web2py ... merci, Luis. On Mon, Jul 4, 2011 at 4:54 PM, Richard Vézina ml.richard.vez...@gmail.comwrote: Maybe you could find some inspiration from this project for Django : http://code.google.com/p/django-dynamic-formset/ You need to install Django to test it... What you seems to do is adding an arbitrary number of input for a given field... Following good database design pratice you will normalise your schema... I had try to find a solution similar to django dynamic formset, but I give up in the pass. You have this thread that could maybe bring some answer : http://groups.google.com/group/web2py/browse_thread/thread/50af0d67554c94d9/ad553c6a5514ecc7?pli=1 Web2py let you do this : http://www.web2py.com/book/default/chapter/07?search=filter#One-form-for-multiple-tables But you can't have fields with the same name in your table... Finally it maybe possible with component now to load a arbitrary number of fields inputs for a given table and with jQuery submit the differents forms as one I would investigate in that direction too... Good luck Richard On Mon, Jul 4, 2011 at 7:17 PM, Luis Goncalves lgoncal...@gmail.comwrote: Hello Richard! I looked at this, but wasn't sure how it could help -- what I need is a way for a (non-technical) admin to create profile forms with arbitrary fields (through a friendly web interface), and then users to be able to view and edit their (run-time reconfigurable) profiles. At any rate, the method I described above seems to work quite well, thanks to web2py's versatility, allowing me to define forms programmatically (excerpt below). I was wondering if there was a more clever/efficient/proper way to do so. Perhaps not! Thanks!! Luis. for field in event_fields: # see if person has a pre-defined value found = False for my_efield in me.event_field: if my_efield.display_title == field.display_title: found = True break if found: if field.data_type == 'string': new_input = INPUT(_type = field.data_type, _name = field.id, requires=IS_NOT_EMPTY(), _value=my_efield.data ) form[0].insert(-2, TR(field.display_title+':', new_input )) elif field.data_type == 'text': . else: if field.data_type == 'string': new_input = INPUT(_type = field.data_type, _name = field.id, requires=IS_NOT_EMPTY()) form[0].insert(-2, TR(field.display_title+':', new_input )) elif field.data_type == 'text':
[web2py] How to call user/register with pre-defined fields (name, email)?
Hello! The website I am developing will be invitation only: - a user gets an email invitation to register with a link to the site (with an identifying token in the link) - the link takes the user to the website, where he can register - to register, he need only define the password, since the person's name and email is already known (login will be email/password) (a confirmation email is still sent, before they can log in) ? How do I call user/register with the person's name and email already filled out, and non-modifiable, so that they only need to define a password ? Thanks!!! Luis.
Re: [web2py] How to call user/register with pre-defined fields (name, email)?
Thanks, pbreit, for the link! Long thread!!! I read it all, but am still unclear how to force registration with a pre-defined name and email (I'll have DB entries such that each unique invite token is associated with a pre-defined name and email). I was hoping to do something like this: def user(): if request.args(0)=='invite': # person has clicked on their invite which takes them to default/user/invite?token=aalsfjlkajflasjflkasjdfl # use the token to look up name and email invite_info = db( db.invite.token == request.vars.token ).select().first() form = auth() # ??? how to make it a registration form ??? # ? Somehow, insert predefined name and email into registration form, #and make them READONLY ? form.first_name = invite_info.first_name ? how to make the field READONLY ? (I think I should change the db.auth definition in db.py !) ? form.last_name = ... ? form.email = return dict(form=form) However (aside from not knowing how to set the fields), this does not work: - a simple test case with dummy code returns 404 Not Found unless I comment out the call to form=auth() the test case: if request.args(0)=='invite': form = auth() response.view = 'default/invite.html' return dict(msg='hello', magic='banana', results='tada') (commenting out form=auth() makes it fine, otherwise 404 Not Found) I suppose auth() was not designed to be manipulated this way? Ultimately, what I don't know how to do is to create a registration form with predefined name and email, so the user just has to pick a password. Thanks!!! Luis.
Re: [web2py] How to call user/register with pre-defined fields (name, email)?
That's a great idea, David! I think I need to know, then: - how to programmatically create registered users - how to programmatically send them the 'reset password' link. Ideally, the person that can invite users will have a simple webpage form where they can input names and email addresses, and upon form submission the accounts get created and invite-as-reset-password emails get sent out. Thanks for the idea! I'll try to figure it out - but if anyone already knows how to do the above steps (second one is probably easy), I'd really appreciate the time-saving help!!! Luis.
[web2py] how to implement database tables with one level of indirection?
Hello! How do I make a database table where the fields are defined by another table? For example, suppose some users of my system are event organizers, and they can define what fields would belong in a person's profile. Then, attendees of that event have to fill out a profile with those specific fields. What is the best way to represent this information (the fields relevant for an event's profile, and the event profiles of users) in a database? What I have been thinking of so far is to define a table that holds the definitions of profile fields: db.define_table('event_profile_field', Field('event', db.event), Field('display_title','text'), Field('data_type', requires=IS_IN_SET('string','text','checkbox','list')), Field('display_order', 'int')) and then each user's profile is built up of multiple entries of the following: db.define_table('event_profile_entry', Field('person', db.person), Field('event', db.event), Field('event_profile_field', db.event_profile_field), Field('data') # XXX we need data to be of different types However, as indicated above by the comment, I'm not sure if it is possible to store different data types in the event_profile_entry.data field. (I suppose I could just make it be 'text' type and have the code know that a checkbox can only be True or False, for example). Is there a more efficient/smarter way to do this? Thanks, Luis.
[web2py] proper way to mobile and desktop 'skins'
Hello! I need to customize my views so that they look good on a computer screen and on a smart phone. One way to do so, It think, is to have separate layout definitions and then do something like: {{if session.platform == 'mobile':}} {{extend 'mobile-layout.html}} {{else:}} {{extend 'desktop-layout.html'}} {{pass}} This does not seem to be working - I get lots of syntax errors (can't even figure out where they are!) Is this approach wrong? Is it possible to have a conditional extend ? Is there a smarter/better way to make the view rendering platform dependent? Thanks, Luis.
[web2py] Re: proper way to mobile and desktop 'skins'
Thanks for the quick reply, Anthony!!! We may try the following : break layout.html into header and footer (everything before and after body), then instead of using {{extend}} we will use conditional {{include}} statements at the top and bottom of each view. That will still give us bytecode compiling, and a fairly clean/straightforward way to have multiple platform dependent layouts (with minimal code change, and maximal code reuse!). Thanks for your insight!!! Luis.
[web2py] how to use contrib/login_methods/linkedin_account.py
Hello! I've been trying to use login via linkedin using the contrib/login_methods/linkedin_account.py module. Off the bat, I got the error : AttributeError: 'module' object has no attribute 'LinkedIn' (this is the same problem Kuba mentioned on nov 12 2010) the reason is that linkedin_account.py line 15 should be from linkedin import linked in instead of import linkedin With that fixed, the error goes away, but authentication fails, with linkedin giving the error We were unable to find the authorization token I think the problem may be that I am not passing linkedin the proper RETURN_URL. Presumably, it should be the URL of a controller that knows how to parse out the oauth_verifier key that linkedin will return (according to the README of the python-linkedin module (version 1.5) ) What should the RETURN_URL be for a web2py application? NOTE that in my case I am developing this in my sandbox app, not the init app that web2py defaults to. NOTE also that by manually executing (in an interactive shell) the instructions in the python-linkedin module README (with the sole exception of doing api.accessToken(verifier='12345') instead of just api.accessToken('54321') ) I was able to authenticate and read profile and connections information, so there is just something wrong I am doing with web2py. Can anybody help? Is RETURN_URL the problem? Thanks!!! Luis.
[web2py] Re: how to use contrib/login_methods/linkedin_account.py
An update (getting closer, but still problems): It seems there are a couple more errors in linkedin_account.py: There is an extraneous command which must have been left over from sample code: profile = self.api.GetProfile(profile).public_url = http://www.linkedin.com/in/ozgurv; This line overwrites the reading of the current user's profile, and should be removed. Also, the call return self.api.getAuthorizeURL(self.token) should be return self.api.getAuthorizeURL() according to the python-linkedin module README instructions. With those fixes, I now no longer get the error We were unable to find the authorization token. However, now I am stuck in an infinite loop: I am always stuck on the linkedin Grant access page, and pressing the continue button keeps returning to the same page. I realize that given the existing bugs in the code, it is unlikely that anyone has actually used it, but does anyone have a clue as to why after granting access on linkedin I am not logged in and back to the app? It seems web2py does not respond properly to the access grant. If anyone can help, it will be greatly appreciated!!! Trying to debug Auth() is going to be quite slow and painful to a web2py newbie like me!!! Thanks!!! Luis.
[web2py] Re: how to use contrib/login_methods/linkedin_account.py
One more clue: In the infinite loop, every loop through the linkedin grant access (/oas/oauth/authorize) page has a new oauth_token, such as https://www.linkedin.com/uas/oauth/authorize?oauth_token=f9eef16e-4f45-4f5e-aa5f-82ab18ad3a16 L.
[web2py] Re: How to implement a fail whale for a web2py website?
Thanks, Massimo! I thought that (redundantly) routes_onerror = [ (r'sandbox_luis/*', r'/sandbox_luis/static/fail.html') (r'*/*', r'/sandbox_luis/static/fail.html') ] would catch all errors, but https://domain.net/sandbox_luis/default/contact_person? results in Bad Request and https://domain.net/sandbox_luis/default/contact_pers results in invalid function (default/contact_pers) How do I detect and re-route these kinds of errors? Thanks, Luis.
[web2py] where is facebook class GraphAPI() ?
This seems like a silly question, but I can't figure it out! Trying to follow the example in the book to use openAuth2.0 and facebook's graphAPI, we need to from facebook import GraphAPI as suggested, I installed pyfacebook first via apt-cache search pyfacebook -- apt-get install python-facebook (but that seemed not to be it) and then via git clone https://github.com/sciyoshi/pyfacebook.git However, it seems that neither one of these defines class GraphAPI() so that I get a web2py error : from facebook import GraphAPI ImportError: cannot import name GraphAPI Are these both the wrong versions of a python facebook module? Where can I get the proper one? Thanks, Luis.
[web2py] Re: where is facebook class GraphAPI() ?
Awesome! Thank you! Will check it out! Luis.
[web2py] How to access facebook graph of logged in user
I've been trying to use OAuth2.0 and the facebook module to allow a user to login to my site, and then use the facebook API to obtain info about them via GraphAPI. The web2py manual (8.1.6, subsection OAuth2.0 and facebook) describes two methods, the first to login to your own app, the second to a specific [user's] Facebook to access its API. I think the second one is what I want. I followed the example: from facebook import GraphAPI ... class FacebookAccount(OAuthAccount): ... auth.settings.login_form = FacebookAccount(globals()) But when I try it out, I get the error message from facebook: { error: { type: OAuthException, message: Invalid redirect_uri: Given URL is not allowed by the Application configuration. } } I noticed that the redirect URL that is shown in the browser seems not to be that of the website running my web2py app (it has it's own domain name), but rather the IP address of my local connection at home (emphasized with bold and large font in the URL string below): https://graph.facebook.com/oauth/authorize?redirect_uri=http%3A%2F%2F* 69.234.184.92* %2Fsandbox_luis%2Fdefault%2Fuser%2Flogin%3F_next%3D%252Fsandbox_luis%252Fdefault%252Findexresponse_type=codeclient_id=219317251425055 What have I done wrong, or what else do I need to do? (I have registered the app on facebook, and defined the site URL and site domain there.) Thanks, Luis.
[web2py] How to implement a fail whale for a web2py website?
Is there an easy/straightforward way to implement a fail whale for a web2py website? I've noticed strange errors (some sort of timeout) when uploading files (running on Amazon ec2), and of course, the site is in beta and bad things may happen. I'd like to have a graceful landing page the user is taken to irrespective of what error occurred. Once there, the user can click to start over. It's OK to give up admin ticket tracking, I just don't want user to see strange errors, whatever they may be. Thank you, Luis.
[web2py] how to include profile photo from Janrain in auth_user?
I have Janrain working as a login method (thanks to the instructions in the web2py manual, and sample code in default app). I'd like to include the profile photo (that, say, facebook provides via janrain) as part of the user profile. I had my own function based on the sample code at the Janrain github, but so far it doesn't work. The reason, I believe, is that the token that Janrain provides can only be used once. In my code, either I let user/login use the token, and then my function can't retrieve the photo, or I can use the token (with code in user() that detects a request.vars.token), but then the web2py login procedure can't use the token, and the user can't even login. I imagine that I could hack away at gluon/tools.py to include retrieving the profile photo along with the other user data during the login process, but I'm sure that's not the easiest or proper way to do things. Does anyone have, or can anyone provide an example of the proper way to do it? Thanks!!! Luis.
[web2py] Re: Social network plug-in
Ciao Massimo! Is it now available somewhere for download? It will be very useful!!! Thanks, Luis.
[web2py] Re: How to not show the delete file checkbox
Excellent! Thank you both! Before I had [file | (cbox) delete ] requires=IS_IMAGE() got rid of the delete and checkbox, but now I am still left with [file] (a link to download the file) Might have to do server-side DOM parsing to get rid of that ... Thanks!!! Luis.
[web2py] Re: How to not show the delete file checkbox
Thanks for the reply! I tried that, but it didn't do what I want. I wasn't very clear in explaining what I'm trying to do (sorry about that!). I have a file upload field in my SQLFORM, and it has a choose file button, and right next to it a [file| (chk-box) delete] element.. I want to get rid of that element with the checkbox so that you can't delete the file. Maybe that's not possible easily? It's part of the 'upload' field type? Thanks!! Luis.
Re: [web2py] Re: How to not show the delete file checkbox
Hi Richard! I'm displaying the form to the user for them to update it. There are several fields in the form, and one of them is an image ('upload' field). I just don't want to display the delete file checkbox for the image, so that the user can't delete the image. They can upload a new one, but they can't delete it to not have an image. The record itself is not to be deleted either, but that's not even an option for the user right now. Thanks!! Luis
[web2py] How to not show the delete file checkbox
Is there a way to avoid showing the delete file checkbox in a form? Thanks, Luis.
[web2py] how to set a default image for an SQLFORM 'upload' field?
Haven't been able to find any examples showing how to define a default image for an upload field of a db table (headshot for a person's profile). Is it possible? Does anyone know how? thanks! Luis.
[web2py] Re: how to set a default image for an SQLFORM 'upload' field?
Forgot to mention, I need this on google appengine. My hack so far: - create a new DB table, 'default images' db.define_table('default_images', Field('name', requires=IS_NOT_EMPTY()), Field('uploaded','upload', requires=IS_NOT_EMPTY())) - create a admin-only function which allows upload of default images - now when a new user is to be created, I can pre-populate their 'person' record with the default image: default_headshot = db(db.default_images.name == 'default_headshot').select().first() new_me = db.person.insert(email = session.auth.user.email, first_name = session.auth.user.first_name, last_name = session.auth.user.last_name, head_shot = default_headshot.uploaded, head_shot_blob = default_headshot.uploaded_blob) # below doesn't work # head_shot = URL(c='static', f='images', 'default_headshot.jpg')) form = SQLFORM(db.person, new_me) This works, except that the first time the controller runs and creates the new record, the SQLFORM does not display the image. On subsequent calls, (if the person wants to change their profile info), it does show properly. Is there a smarter/easier way??? thanks, Luis.
[web2py] Re: how to set a default image for an SQLFORM 'upload' field?
Perfect! Thanks!! These tidbit examples are invaluable! As I learn web2py, I am taking notes of where I get stuck, in order to eventually provide suggestions for improving the doc/manual from the novice's eyes (once you already know everything, it isn't as obvious what's missing). The documentation and manual are already quite excellent, part of the reason why I chose web2py (besides, the very clean, structured design, and power!). This is a great example because it shows - how to combine logical expressions to select between user data and a default - how to use URL and IMG with uploaded and static data (didn't find that in the manual or online examples) I'm also re-reading the HTML Helpers in The VIews chapter :) ..and now on to the really hard stuff ... making everything look good ... Thank you!!! Luis.
[web2py] Re: How do I modify the form on default/user/profile ?
Hello Annet! Your example helps a lot! I'm not yet familiar enough with web2py/ python to realize that I could just extend the empty user() controller (and I don't think I came across an example in the web2py book or the online examples). Since I already had my own my_profile() controller, what I did is, def user(): ... if request.args(0)=='profile' my_profile_dict = my_profile() return my_profile_dict ... I don't know if that's proper usage/style for python/web2py, but it works fine!! Thanks!!! Luis. On May 28, 11:22 pm, annet annet.verm...@gmail.com wrote: Hi Luis, I am not sure I understand your question correctly, but as far as I know default/user/profile is based on the auth_user table, to which you can add any field you want e.g. # Custom Auth table definition db.define_table(auth.settings.table_user_name, Field('username', length=20, unique=True), Field('first_name', length=128, default='', comment='required'), Field('last_name', length=128, default='', comment='required'), Field('email', length=128, default='', unique=True), Field('hide_email', 'boolean', default=False), Field('phone', length=64, default=''), Field('homepage', requires=IS_EMPTY_OR(IS_URL())), Field('facebook_access_token', writable=False, readable=False), Field('flickr_user', label='Flickr Screenname'), Field('flickr_id', writable=False),#, readable=False), # computed, see below Field('twitter_user'), Field('bio', 'text', default=''), Field('ref_friends' , 'list:reference '+auth.settings.table_user_name, writable=False, readable=False), Field('password', 'password', length=64, readable=False, label='Password'), Field('registration_key', length=512, writable=False, readable=False, default=''), Field('reset_password_key', length=512, writable=False, readable=False, default=''), Field('registration_id', length=512, writable=False, readable=False, default=''), Field('record_created', 'datetime', default=request.now, writable=False, readable=False), Field('record_updated', 'datetime', default=request.now, update=request.now, writable=False, readable=False) ) Whether a field is editable in default/user/profile depends on writable and readable being True or False. In one of my apps I wanted the form to display differently, I solved this by adding the following lines of code to the default/user function: form=auth() if isinstance(form,FORM): form[0][-1] [1].append(INPUT(_type=button,_value=Cancel,_onclick=window.location=' %s';%URL(r=request,c='usercms',f='index'))) if request.args(0)=='login': form.element(_type='submit')['_value']='Login' if request.args(0)=='profile': response.view='default/profile.html' return dict(form=form) I hope this point you in the right direction. Kind regards, Annet.
[web2py] Re: Do I have to re-invent the wheel to display and manage messages between users on a website?
Yes, I have something like that already. But I also want a user to see all the messages he has sent/received (as a list showing sender, date, and subject), and be able to view the entire message and reply to it upon selecting one. Not hard stuff, just would be nice to have something already done and polished rather than hacking my way at it from zero ... thanks, Luis. On May 29, 5:52 am, Bruno Rocha rochacbr...@gmail.com wrote: You can reuse some code from this appliance: contact form (store in dbb then sends an email)http://web2py.com/appliances/default/show/10 http://web2py.com/appliances/default/show/10 -- Bruno Rocha [ About me:http://zerp.ly/rochacbruno] On Sun, May 29, 2011 at 2:09 AM, Luis Goncalves lgoncal...@gmail.comwrote: Hello! I'm building an application where logged-in users can send messages to each other (the message gets sent to the recipient's normal email, and they use a link to come back to the site and reply). I want a page (ie, controller, view, (and model)) that allows the user to see the messages sent and received, and manage them (delete, reply, etc). Basically this part of the website is like an email system, except that you don't ever know the other person's email, and can only contact them through the site. I was hoping that something like that already exists (a web2py messaging slice, perhaps?). I'm sure I can implement it, but it would be clever to use something that already exists (and is likely to be a more thorough and featured implementation) rather than hacking it up from scratch. I have been searching, but haven't found anything. Does anyone know of anything available that I can use? Thanks!!! Luis.
[web2py] Re: Do I have to re-invent the wheel to display and manage messages between users on a website?
Yes, in the end likely I'd have to customize whatever I found. Still, may have been a good base to start from. thx, Luis. On May 29, 4:44 am, Albert Abril albert.ab...@gmail.com wrote: I guess you should make a model called messages, which you must relate it within users. Depends how you want to it working. 2011/5/29 Luis Goncalves lgoncal...@gmail.com Hello! I'm building an application where logged-in users can send messages to each other (the message gets sent to the recipient's normal email, and they use a link to come back to the site and reply). I want a page (ie, controller, view, (and model)) that allows the user to see the messages sent and received, and manage them (delete, reply, etc). Basically this part of the website is like an email system, except that you don't ever know the other person's email, and can only contact them through the site. I was hoping that something like that already exists (a web2py messaging slice, perhaps?). I'm sure I can implement it, but it would be clever to use something that already exists (and is likely to be a more thorough and featured implementation) rather than hacking it up from scratch. I have been searching, but haven't found anything. Does anyone know of anything available that I can use? Thanks!!! Luis.
[web2py] How do I get a controller to return back to the page that calls it (when it can be called by many pages)?
Hello All! There is a database action that I want to do in several views. Right now, I have it implemented as a link in each view as a href=db_action?id={{=item_id}}Toggle Status/a How do I get my db_action() controller to return back to the page with the link that called it? Is there a way to cause the browser to do the equivalent of the back button? Something like: response.view = find_the_controller(request.env.http_referer) return dict() won't work because I'm not returning the proper dictionary for the referring controller. Maybe something like: dict_from_referring_controller = run_referring_controller( request.env.http_referer ) # ? do I have to define the response view? return dict_from_referring_controller Perhaps the nicest/cleanest implementation would be with AJAX/JQuery, but I haven't learned that yet. Is there a way to do it with a href links? Or is that super-bad form? Thanks! Luis.
[web2py] a href= misbehaves on a view of a controller with arguments
Hello! I have a controller, my_control(), that can be called by itself, or with two arguments , ../default/my_control/AAA or .../BBB In the associated view, my_control.html, I have some href links that call a new controller: a href=compute_value?id={{=stock.id}}Compute Value/a If I was on the URL .../default/my_control this works fine, because the href becomes .../default/compute_value?id=9 but if instead I am on the URL ../default/my_control/AAA then the href breaks, because it becomes .../default/AAA/compute_value?id=9 That is, it seems that a href = ... only replaces the very last element from the URL Is there a better way to generate a URL to my controller, irrespective of what page (with or without arguments) I am on? Thanks!!! Luis.
[web2py] Re: a href= misbehaves on a view of a controller with arguments
I figured it out ... .. use the powerful URL() helper function! sorry for the 'spam' L.
[web2py] Re: a href= misbehaves on a view of a controller with arguments
Thanks! I was confused, but the URL doc makes it clear that there are applications, controllers, functions, arguments, and variables. Thx, L.
[web2py] Re: How to display a multi-line string variable properly?
Perfect!!! Thank you!!! Luis. On May 27, 10:28 pm, pbreit pbreitenb...@gmail.com wrote: I think you have to search/replace: {{=XML(str(message_body).replace('\n', 'br'), sanitize=True)}} I'm not sure if str() is always necessary or if sanitize needs to be True.
[web2py] Do I have to re-invent the wheel to display and manage messages between users on a website?
Hello! I'm building an application where logged-in users can send messages to each other (the message gets sent to the recipient's normal email, and they use a link to come back to the site and reply). I want a page (ie, controller, view, (and model)) that allows the user to see the messages sent and received, and manage them (delete, reply, etc). Basically this part of the website is like an email system, except that you don't ever know the other person's email, and can only contact them through the site. I was hoping that something like that already exists (a web2py messaging slice, perhaps?). I'm sure I can implement it, but it would be clever to use something that already exists (and is likely to be a more thorough and featured implementation) rather than hacking it up from scratch. I have been searching, but haven't found anything. Does anyone know of anything available that I can use? Thanks!!! Luis.
[web2py] How do I modify the form on default/user/profile ?
Hello Everyone! How do I modify default/user/profile to use my own form (where the profile contains more information)? I think it should be easy, but I haven't found any info or an example yet. Thanks in advance!!! Luis.
[web2py] How to display a multi-line string variable properly?
I have a string variable, message_body, which is multiline (has newlines or \n characters). How do I get it to display properly in an HTML view? simply using {{=message_body}} displays the text all on the same line, ignoring the carriage returns. {{=TEXTAREA(message_body)}} displays properly, but is ugly (unless I can control the number of lines to fit tightly, and make the are non- editable). Thanks in advance! Luis.
[web2py] Re: can't use admin, can't see tickets with localhost google appengine SDK
I'm running on linux (Ubuntu 10.04.2, or my old debian system). I start from a shell with python dev_appserver.py ../web2py/ On my old debian system, this pops up a little window where I type in my admin password and hit the start server button. On the new Ubuntu system it tells me I don't have the TK Library and I type in my admin password at the prompt. The Ubuntu install is brand new, with the latest GAE (1.5, I believe) and the latest source web2py (for 'normal' users). I'm not sure re-installing would do anything, since it is all fresh! Thx, Luis. On May 25, 10:13 pm, pbreit pbreitenb...@gmail.com wrote: Are you running on Mac, Windows or Linux? Here's the command I run on Mac: python web2py.py -a recycle -i 127.0.0.1 -p 8001' If you are running from command line you don't even use Tk. Are you using one of the binaries or the source code (I prefer source)? Have you tried re-installing?
[web2py] Re: can't use admin, can't see tickets with localhost google appengine SDK
Good idea to copy the files to the debian system and try to see them there! Also good idea to look at the applications/admin/errors directly! I will try! Yes, I've got source code 1.95.1 (stable) for web2py GAE (when you run uploaded from google) uses python 2.5.2. Likewise, web2py recommends on 2.5.2, for backwards compatibility. My debian system has 2.5.2. Perhaps my problem is that I didn't run the setup-web2py-ubuntu.sh !!! I am trying that now! Thanks!!! L. On May 25, 10:17 pm, ron_m ron.mco...@gmail.com wrote: Looks like you get a ticket trying to display the application error ticket. I had that once but I was debugging something in trunk that was broken at the time. You mentioned you have a fully and properly working debain version. I believe it is legit to move the files under errors in your application to the system that works and look at them there using the admin interface. That might help get a handle on it. Also when the admin system gets an error you will find the ticket file under applications/admin/errors. You are using stable from web2py currently 1.95.1? I would be tempted to download the zip file, unpack it and slide it into place where the existing one is now after you rename the top directory of the old one. Then you can run a diff to see if something got changed somehow. Is there a requirement to run GAE on python 2.5? What version of Python is on your debian system where everything is working? I run standalone or under apache with wsgi on Python 2.6.5 without issues. Have a look at web2py/scripts/setup-web2py-ubuntu.sh and you can see the packages that get loaded in there. I wouldn't load in matplotlib or reportlab unless you need them. Ron
[web2py] Re: can't use admin, can't see tickets with localhost google appengine SDK
To make a long story short : it works now! I ran the ubuntu.sh script, and it installed a lot of stuff (still had to instal python-tk manually) tried to run admin, still got errors. Looked at the error log in admin/errors, and compared the file that it said had a syntax error -- it was very different from the same file on my working debian system!!! So somehow, my ubuntu install of web2py was seriously screwed up! Re-installing it from a new download of web2py_src.zip has everything working now!!! Thanks to you both for the help and support!!! Luis. (PS, I come from a Matlab background, and am just now switching to python. The learning curve is not too steep, and I can already see the power of python!!! I'm building a website, and GAE + web2py seemed like the best choice. web2py is awesome!!!) On May 25, 11:57 pm, Luis Goncalves lgoncal...@gmail.com wrote: Good idea to copy the files to the debian system and try to see them there! Also good idea to look at the applications/admin/errors directly! I will try! Yes, I've got source code 1.95.1 (stable) for web2py GAE (when you run uploaded from google) uses python 2.5.2. Likewise, web2py recommends on 2.5.2, for backwards compatibility. My debian system has 2.5.2. Perhaps my problem is that I didn't run the setup-web2py-ubuntu.sh !!! I am trying that now! Thanks!!! L. On May 25, 10:17 pm, ron_m ron.mco...@gmail.com wrote: Looks like you get a ticket trying to display the application error ticket. I had that once but I was debugging something in trunk that was broken at the time. You mentioned you have a fully and properly working debain version. I believe it is legit to move the files under errors in your application to the system that works and look at them there using the admin interface. That might help get a handle on it. Also when the admin system gets an error you will find the ticket file under applications/admin/errors. You are using stable from web2py currently 1.95.1? I would be tempted to download the zip file, unpack it and slide it into place where the existing one is now after you rename the top directory of the old one. Then you can run a diff to see if something got changed somehow. Is there a requirement to run GAE on python 2.5? What version of Python is on your debian system where everything is working? I run standalone or under apache with wsgi on Python 2.6.5 without issues. Have a look at web2py/scripts/setup-web2py-ubuntu.sh and you can see the packages that get loaded in there. I wouldn't load in matplotlib or reportlab unless you need them. Ron
[web2py] Re: can't use admin, can't see tickets with localhost google appengine SDK
Thank you, Arbie! For a while I was using a Windows (windose) machine with the Google App Engine Launcher, and so had no console to see. Then I switched to linux, and didn't even notice that the console echoed the error output! Curiously, with an old debian machine with python 2.5.2, admin and tickets work fine (through the browser) if I run the web2py server directly instead of through the GAE. I found this the best way to debug. Occasionally I switch to running through the (localhost) GAE to make sure everything works there too. One frustrating thing (so far) is that it seems that it is much harder to debug errors in views (.html files) than in controllers, because the line numbering is all mixed up (due to the {{extend *.html}} statements). On my Ubuntu 10.04.2 machine, admin and tickets don't work. Not sure why, but might try to investigate the difference between it and my old debian machine, since it's useful functionality! Thanks for your help!!! L. On May 20, 12:40 am, Arbie Samong phek...@gmail.com wrote: Admin is disabled there. If you want to check for errors go see your console. On production, check the server logs at the left menu on your dashboard. Regards, Arbie On May 20, 11:08 am, Pierluigi Martini lgoncal...@gmail.com wrote: I am trying to deploy an application on GAE using web2py. I am running GAE SDK 1.5 on my localhost (ubuntu 8.10 , python2.5 with ssl module but not python-tk) Usingpython dev_appengine.py ../web2py works fine execpt that: If (in the browser) I try to run the admin app, or, more importantly, if I try to see a ticket due to a bug in my code, I get the error: admin is disabled because insecure channel How can I run admin and see tickets when using web2py with GAE SDK on localhost??? Note that python web2py.py works fine, with admin and tickets (although I have to type my admin password on the console because I don't have python-tk -- don't know if that makes a difference). I've looked online for quite a while and haven't found an answer yet. I hope it is possible to get debug info (tickets) running web2py with GAE! Thank you! L.
[web2py] Re: can't use admin, can't see tickets with localhost google appengine SDK
In reply to your and ron_m's messages: On Ubuntu 10.04.02 with python 2.6.5, When I have a simple error in my python controller (say, return dict(ans=ans) , where ans hasn't been defined), if I run python web2py.py : I first get the web-browser error: Internal error Ticket issued: welcome/ 127.0.0.1.2011-05-26.04-31-29.b6c7d52d-b576-406b-ba3d-74308226e85b and clicking on the ticket opens another tab with another Internal error ticket (ad infinitum if I keep on clicking) invalid request I also don't see any messages on the terminal where I ran web2py.py. If I run the gae with python dev_appserver.py ../web2py/ I first get an Internal error ticket, and if I click on it, I get a new tab with invalid request (and no link). At least with the GAE I can see the error traceback in the shell running the server! Permissions are: drwxrwxr-x 2 zb zb 4.0K 2011-05-25 21:27 errors/ and in errors/ -rw-r--r-- 1 zb zb 87K 2011-05-25 21:27 127.0.0.1.2011-05-25.21-27-52.12358da4-3e47-461b-9fae-fd190aebfb65 which seems to be OK for viewing So it's still a mystery why I don't get web tickets and admin! (Note: I am at least missing the Tk library, because I get a warning when I run web2py.py: WARNING:web2py:GUI not available because Tk library is not installed -- does not seem that has anything to do with it, though, other than being an indication that I don't technically have everything that web2py needs, which oddly enough I did have on my old debian system!) Thank you, pbreit and ron_m for your help and advice!!! Luis. On May 25, 9:03 am, pbreit pbreitenb...@gmail.com wrote: I run 10.04.2 and admin works fine. Are you getting error messages? I have found it's usually quite easy to resolve HTML errors. The traceback usually includes the view file's line number and/or the code listing shows the view file converted into Python which is easy enough to identify.