Menu
  • HOME
  • TAGS

web2py CAS custom fields

single-sign-on,web2py,cas,jasig

There were issues on web2py's CAS 2.0 implementation where the XML envelope was inspected but not the actual Attribute structure. I made some changes to a fork and submitted a pull request. https://github.com/yusufk/web2py...

Can you add a custom field/column to a SQLFORM.grid?

web2py

You can use the "links" argument: grid = SQLFORM.grid(query, fields=[db.table1.total, db.table2.count], links=[dict(header='Total - Count', body=lambda r: r.table1.total - r.table2.count)]) By default, all "links" columns appear on the right. You can change that by setting the "links_placement" argument to either "left" or "both"....

Can not run the web2py scheduler using postgresql database

postgresql,web2py,scheduler

I'm having the same error. Development environment: windows version of web2py w/ included web server and sqlite Production environment: web2py tied to Apache on Linux web server and PostgreSQL. To get the actual error cause, I tweaked gluon/scheduler.py. After removing the guilty try/except of Scheduler.send_heartbeat() I got the following error:...

Migrating passwords from web2py to Django

django,passwords,web2py,sha512

According to this post a Python snippet to recreate the convention used in web2py would be the following: from hashlib import md5 import hmac hmac_key = '<your secret key>' password = 'insecure' thehash = hmac.new(hmac_key, password).hexdigest() print thehash web2py uses hmac (which is your secret + the plaintext of the...

wep2py doesn't write into sql base while function is in endless loop

python,sql,web2py

In your infinite while loop, the data are not committed in the DB. Web2py automatically commits data at the end of a function from a controller. But in your case, the function main() never exits so, Web2py does not commit the data. If you want to see the updated data...

Web2py - Insert Record in Second Tabel on Registration

web2py

If you started with the scaffolding app, in the default.py controller, you probably have a function like: def user(): return dict(form=auth()) Calling the auth object handles processing for all Auth actions (the particular action is determined based on the first URL arg after /default/user -- so, /default/user/register triggers the registration...

Problems with ajax and session variable in Web2Py

javascript,python,ajax,session,web2py

The model file is executed on every request, so you are resetting session.carrinho back to an empty list on every request. Instead, in the model, this: session.carrinho = [] should be something like: session.carrinho = [] if session.carrinho is None else session.carrinho ...

web2py: module function that behaves normally in shell fails browser mode

function,python-2.7,web2py

It looks like you're just trying to remove None values from a dictionary, so instead, why not just create a function to do that: def remove_none(d): [d.pop(key) for key in d.keys() if d[key] is None] Then you can do: col = remove_none(dict(field=attr.columns.tolist(), title=None, width=None, attributes=None)) Or if you want to...

ImportError: cannot import name secure_dumps

web2py,data-access-layer,bottle

The solution to this problem was to use gluino instead of gluon. gluino is a port of web2py to Bottle and other web frameworks and can be downloaded here.

Web2py Views & URL Patterns

web2py

The best approach depends on exactly what needs to differ in the view based on the different categories. Let's say you have a URL like /myapp/default/index/Small/Happy. In the index function, you could do something like: def index(): size = request.args(0) emotion = request.args(1) data = [code based on size and...

How do i print out a single row record

web2py

If you want to display one record of the result of a query, you could use SQLFOM.grid : def view_post: form = SQLFORM.grid( query = db.post.id==10 ) return dict( form=form ) You can replace 10 for anything you want, or change the query. If you want to check out a...

python parse Json for all null values

python,json,error-handling,web2py

You can use a recursive function to iterate over the values of complex objects while remembering the path you're at (to report back): #!/usr/bin/env python # used to parse the json text import json with open('json.txt', 'r') as f: d = json.load(f) # define list of what your consider as...

web2py: how to customize add.edit forms in SQLFORM.smartgrid?

python,model-view-controller,web,web2py

If you just want to change the form widgets used for particular fields, you do not have to customize the create/update forms directly. Instead, you can just specify the appropriate validators and custom widgets: db.define_table('mytable', Field('field1', requires=IS_IN_SET(['a', 'b', 'c'])), Field('field2', requires=IS_IN_SET(['x', 'y', 'z'], multiple=True), widget=SQLFORM.widgets.checkboxes.widget)) The IS_IN_SET validator will automatically...

Installing an editor plugin in web2py app

ckeditor,web2py

This worked for me: in db.py: from plugin_ckeditor import CKEditor ckeditor = CKEditor(db) db.define_table('wpage', Field('title'), Field('body', 'text',widget=ckeditor.widget), auth.signature, # created_on, created_by, modified_on, modified_by, is_active format='%(title)s') In default.py: @ auth.requires_login() def create(): """creates a new empty wiki page""" ckeditor.define_tables() form = SQLFORM(db.wpage).process(next=URL('index')) return dict(form=form) I used ckeditor.define_tables() in edit() and show()...

running web2py scheduler in production

python,deployment,web2py,production-environment

With Ubuntu 12.04 I make it manually: in /etc/init directory create web2py-scheduler.conf file: description "Web2py scheduler" start on filesystem or runlevel [2345] stop on runlevel [!2345] respawn respawn limit 8 60 exec sudo -u user <path_to_web2py>/web2py.py -K <your_app> in /etc/init.d exec: ln -s /lib/init/upstart-job web2py-scheduler (optional, only if you want...

How to add a SSL certificate after running Web2py 'one step production deployment'

python,linux,ssl,web2py

If you look into the one-step-production-deployment script, you can see that it generated a self-signed cert: echo "creating a self signed certificate" echo "==================================" openssl genrsa 1024 > /etc/apache2/ssl/self_signed.key chmod 400 /etc/apache2/ssl/self_signed.key openssl req -new -x509 -nodes -sha1 -days 365 -key /etc/apache2/ssl/self_signed.key > /etc/apache2/ssl/self_signed.cert openssl x509 -noout -fingerprint -text <...

web2py How to know a user is logged in as admin

python,web2py

To check whether the user of a given application is also currently logged into the "admin" app (which is required in order to access the "appadmin" controller of any application), you can use check_credentials: from gluon import fileutils is_logged_into_admin = fileutils.check_credentials(request) To use this with the Auth.requires decorator, you can...

How to self-submit a web2py-component at change-event

javascript,web2py

With Massimilianos hint and this answer I came up with this solution: Component A (where the drag starts) now contains this script: <script> /* Provides Drag and Drop functionality */ d = dragula([document.querySelector(".drag-start"), document.querySelector(".drag-target")]); d.on('drop', function(el) { var test1, test2, id; test1 = 'test1'; /* Some information */ id =...

How Initialize web2py with password in terminal

python,web2py,initializing

The -a argument sets the password: alias w2p="python web2py -p 8000 -a yourpassword" ...

Web2py: Submit Javascript Vars with Form

javascript,web2py

Add an id to your form or to a div in your form (calling it '#addinput' here), then append a hidden input once your button is clicked: <script> $('#button').click(function(){ var cost = +($("#cost").text().replace('$','')); $('#addinput').append('<input type="hidden" name="id" value="'+cost+'" id="id">') }); </script> ...

Web2py: Limiting a dropdown value only to Logged in user

python,forms,validation,web2py

If the only email address allowed in this field is that of the currently logged in user, then maybe just set that as the default value and don't make the field writable: Field('coordinator', writable=False, default=auth.user.email if auth.user else None, update=auth.user.email if auth.user else None) However, a better approach might be...

Web2py - Custom Registration & Login Form in One

web2py

In your controller, auth.login_bare is the trick: email, password = request.post_vars['email'], request.post_vars['password'] if not auth.login_bare(email, password): db.auth_user.insert( first_name=None, last_name=None, email=email, password=db.auth_user.password.requires[0](password)[0] ) auth.login_bare(email, password) #redirect Note, auth.login_bare will automatically login the user if username and password exist. If the combination doesn't exist, then we manually insert a user into...

Web2py orderby, limitby

mongodb,web2py

It should be: orderby = ~db.news.date See details in the documentation....

Multiple Validators for a single field

python,validation,web2py

If you put the IS_IN_DB validator in a list, it will no longer generate the select widget. Instead of putting the validators in a list, you can use the _and argument: db.nsksystem.nskreleaseid.requires = IS_IN_DB(db, 'nskrelease.releaseid', _and=IS_NOT_IN_DB(db(db.nsksystem.nskmachinename == request.vars.nskmachinename), 'nsksystem.releaseid', error_message='Machine is already registered to the specified release.')) ...

The correct way to implement login with google account

oauth-2.0,google-plus,web2py,janrain

This is how I did it. Put this in models/db.py and don't forget to define your client_id and client_secret above. class googleAccount(OAuthAccount): AUTH_URL="https://accounts.google.com/o/oauth2/auth" TOKEN_URL="https://accounts.google.com/o/oauth2/token" def __init__(self): OAuthAccount.__init__(self, client_id=client_id, client_secret=client_secret, auth_url=self.AUTH_URL, token_url=self.TOKEN_URL, approval_prompt='force', state='auth_provider=google', scope='https://www.googleapis.com/auth/userinfo.profile...

Web2py - Howto Auto Convert Username field to uppercase

python,ldap,web2py,web-frameworks

Edit4: Fixed the issue: The solution def user(): if request.args(0) == 'login' and request.post_vars.username: request.post_vars.username = request.vars.username = request.post_vars.username.upper() # changes field to all uppercase return dict(form=auth()) ...

How to use concat in web2py dal select query?

sqlite3,web2py

The .select() method can take SQL expressions as arguments in addition to fields, so you can do: val = "'val_' || mytable.id" rows = db(db.mytable).select(val) print rows[0][val] Note, when using an expression in the select, the resulting value is stored in the row object with a key equivalent to the...

Multiple virtualhosts for two python sites, one dominates

python,apache,flask,mod-wsgi,web2py

For anyone coming here, I've solved my problem. It was a simple mistake, and I could have sworn I had tried this before. In the configuration for the Flask site, I should have done: ServerName my.domain.com ... WSGIScriptAlias /suburl /Users/myname/suburl/app.wsgi Notice that the ServerName no longer has /suburl at the...

Web2py with Multiple Controllers

web2py

When a function is needed from a controller, the whole controller must be read in; this will be faster the smaller the controller is. Whether it is enough of a difference to warrant the effort, that's what profiling is for. As for when to think about organizing controllers, the best...

web2py SQLFORM.grid () get field values on process

sql,forms,grid,web2py

You can simply define the validator for one of the fields so it doesn't allow duplicates when the other field is also a duplicate, and then let the standard form validation process handle everything: db.define_table('mytable', Field('userid', 'reference auth_user'), Field('otherfield', requires=IS_NOT_IN_DB(db(db.mytable.userid == request.vars.userid), 'mytable.otherfield'))) Whenever a form is submitted, the IS_NOT_IN_DB...

Can web2py be made to allow exceptions to be caught in my PyCharm debugger?

python,debugging,exception,web2py,pycharm

I figured this out by looking through the web2py source code. Apparently, web2py is set up to do what I want to do for a particular debugger, seemingly called Wing Db. There's a constant env var ref in the code named WINGDB_ACTIVE that, if set, redirects exceptions to an external...

Selecting random records and not rendom records in same function in web2py

web2py

You can do a separate query to generate another Rows object and then combine them: rows = (db().select(db.test.ALL, limitby=(0, 5), orderby='<random>') | db(db.test.id == some_id).select()) Just reverse the order if you want the non-random record to come first instead of last....

DataTables Server-side Processing with web2py: how to access the parameters sent to the server

datatables,web2py

In web2py, variables from a POST request are in request.post_vars, variables from the query string are in request.get_vars, and both sets of variables are in request.vars. So, in your controller, you can access those variables via request.vars.iDisplayStart, request.vars.iDisplayLength, etc.

Conditional fields for a SQLFORM.factory in web2py

python,web2py

OK I figured it out. If you examine the page source on the SQLFORM.factory form, you notice that the ids given are "no_table_field1" and "no_table_field2". So, stealing borrowing the code from the JQuery & Ajax chapter of the web2py book, I add this to the end of the relevant view:...

Web2py: Database queries from within layout.html

mongodb,web2py

There is no security issue, as the view is executed on the server. However, a better practice would be to move that code to a model file, and then simply display the result in the layout (any objects defined in a model file will be available in the view's execution...

how to let the domin ip point to a web2py app instead of the default “welcome” app

apache,mod-wsgi,web2py

web2py's parameter-based rewrite system allows you to map domains to apps. In routes.py: routers = dict( BASE = dict( domains = { 'domain1.com' : 'app1', 'domain2.com' : 'app2', } ), ) The pattern-based rewrite system could be used as well....

web2py - trouble building a query

sql,web2py

A couple of things worth noting there. First of all, to keep things neat, you may want to build a list of queries, and then reduce them using a function like the following: def reduce_query_list(query_list, operator = 'and'): if operator == 'or': return reduce(lambda q01, q02:q01|q02, query_list) elif operator ==...

web2py error: You might need to add explicit type casts

python,sql,web2py

Note that db.homework.receiver is a list:reference type field, so it stores lists of record IDs, not individual IDs. As such, you must use the .contains operator rather than == to check whether a particular ID is included in the list. Internally, list:reference fields are stored as text fields with the...

Callback method in View doesn't evaluate

jquery,web2py

When you upgrade the framework, you also have to upgrade the web2py.js file in your application's /static folder, as that is part of the framework code and required for the JavaScript/Ajax functionality to work properly. UPDATE: Looking at the old and new code, it looks like the implementation has changed....

Kendo UI all elements of grid showing up on Kendo Console, but grid is not rendering

javascript,jquery,kendo-ui,web2py

https://jsfiddle.net/yjzzfpcf/3/ Kendo UI expects { field: asset ... } not { fields: asset ... } Maybe it was an error when you made jsFiddle? If not then thats culprit in your original code....

Google App Engine, Web2Py, and Cron, unable to assign value to attribute for url error

python,google-app-engine,cron,web2py

You're missing a slash in your cron.yaml url specification: cron: - description: test url: /data/default/test schedule: every 2 minutes synchronized ...

How to filter words in db.body

web2py,web2py-modules

You have several options. First, you can create a custom validator that simply acts as a filter. A validator takes a value and returns a tuple including the (possibly transformed) value and either None or an error message (in this case, we want to return None as the second element...

Bootstrap Clockpicker CSS in web2py

twitter-bootstrap,twitter-bootstrap-3,web2py

The problem is not due to any customizations of Bootstrap but due to the standard Bootstrap 2 CSS rules, which include the following: [class*="span"] { float: left; min-height: 1px; margin-left: 20px; } The hours and minutes displayed in the clockpicker have the classes "clockpicker-span-hours" and "clockpicker-span-minutes", respectively, both of which...

mail.send() feature in web2py for bounced email/ email address that doesnt exist

python,email,gmail,web2py

mail.send() is only passing the message to the SMTP server, the response simply states that the server successfully received/accepted the message for further processing. To check this disconnect your computer from the net or intentionally break the mail config and try again - mail.send() should fail since it can't connect...

Web2py: Access row from custom widget

web2py,custom-widgets

Assuming this is for dealing with SQLFORM.smartgrid update forms, you can try something like the following trick: def show_grid(): if 'edit' in request.args: db.mytable.myfield.record = db.mytable(request.args(-1)) return dict(grid=SQLFORM.smartgrid(db.mytable)) The above code adds a "record" attribute to the field object (which will get passed to the widget, where you can then...

web2py - Unit testing @auth.requires_login()

python,unit-testing,web2py,python-unittest

Below is the setup for unittest. The error I made was where I placed the execution of execfile command. class TestBase(unittest.TestCase): def setUp(self): global auth, request, session, response, db self._application = 'contacts' self._controller = 'default' self._pyfile = os.path.join(request.env.web2py_path, request.folder, 'controllers', self._controller + '.py') self.db_link = 'postgres://......._test' db = test_helpers.copy_db(globals(), db_link=self.db_link)...

How to install packages into gluon.contrib with web2py

python,web2py

OK I figured it out: had to move jsonpickle to the site-packages folder instead of gluon/contrib, and then it imported fine.

Fixing cursor issues in Web2Py on Google AppEngine?

python,google-app-engine,web2py

This issue was fixed by updating to Web2Py v2.11.2

web2py: global name 'crud' is not defined

python,web2py

BTW. Crud is an old API which we no longer support. form = crud.create(db.post) should be rewritten as form = SQLFORM(db.post).process() ...

Determine the selected radio button in Web2py

web2py

Assuming you are using SQLFORM, the selected value will be in request.post_vars.selection_type.

Making a function to abstract a web2py DB call

web2py

In the function, options will be a list, but .select() does not take a list, so you must use the * notation to expand the list into a set of arguments: .select(*options) Also, to make the function more general, you might also want to allow the keyword arguments of the...

How to create DB-Tables on runtime

web2py

By default, the URL identifies a controller and function within that controller, and the framework runs that function (after executing the model files). You cannot define a function in a model file and then call that function by including its name in a URL. Instead, you should either put the...

How to change '_class' of Web2py autocomplete widget

web2py

The autocomplete widget is a TAG object that contains two components, the first of which is the INPUT element. So, do something like: if p == 'subject': form.custom.widget[p][0].add_class(classes) Note, you can use the add_class method to add classes to an element that has an existing class. Also, instead of manually...

Web2py Authentication for Restful service and also application users

web2py,restful-authentication

Basically you want two types of authentication for a web2py Restfull service. This could be achieved using a more general auth.requires decorator, @auth.requires(custom_auth, requires_login=False) where custom custom_auth is a function defined in models, def custom_auth(): """Just a prototype that needs to be extended""" web2py_login = auth.user is not None other_login...

Using validators to constrain the acceptable domains for a db field that stores a URL?

web2py

You can add the IS_MATCH validator: IS_EMPTY_OR([IS_URL(), IS_MATCH(r'google\.com$|yahoo\.com$|bing\.com$')]) ...

Web2py - Run Loop & Break Loop Without Locking Application

python,selenium,web2py

When it comes to long-running tasks, it is a bad idea to execute that task in the web2py model, view, or controller, as this will block the entire request thread until the task completes. In the meantime, this also forces the server to open new threads for subsequent requests to...

Pass Variable to Model

javascript,json,web2py

The following code: {{=XML(response.json(GetFiles(VARIABLE)))}} is Python code that gets evaluated on the server before the HTML page is delivered to the browser. Therefore, it only recognizes variables that have been defined in the Python environment. On the other hand, the following code: VARIABLE = 'teststring' is Javascript, and doesn't get...

Web2py - Setting Title & Meta Tags in Views

web2py

First, do not put any HTML before {{extend 'layout.html'}}, as anything before the extend will be inserted before the beginning of the HTML in 'layout.html', which itself begins with the opening <html> and <head> tags (so, your example inserts an entire <head> section before the opening <html> tag of the...

web2py send value from a form to another controller

python,web2py

Just post the form to the URL that you want to handle the data: <form enctype="multipart/form-data" action="{{=URL('output', 'index')}}" method="post"> ...

Groupby and having in web2py

web2py

It looks like there is no need for rows_two, as each of the records in rows already contains a pic, so you can just use any one of those. So, change your code to the following: def index(): rows = db().select(db.test.ALL, limitby=(0, 5), orderby='<random>') return locals() In the view: <div...

Web2py: Can you password protect a page?

web2py

Web2py has some powerful access control features built in. See this link. Basically you can create groups and add/remove users (members) to these groups. If the user is a member of a group, you can allow or disallow access to certain things. For example, lets create a group and add...

How to use the Comodo certificate in Web2py?

ssl,web2py

Finally got it working! It turns out to be the Web2py 'One step production deployment' script is not complete. It leaves out the 'SSLCertificateChainFile' option when it configures the Apache server. So by adding this line: SSLCertificateChainFile = path_to_your_ca-bundle_file Below the line 'SSLCertificateKeyFile /etc/apache2/ssl/self_signed.key' will do the work....

My custom views are not rendering, no error or ticket is provided by web2py

python,matplotlib,web2py

The problem is that your dashboard function makes the following calls: myplot() myhist() myplot2() Each of those functions sets the content-type header to "image/png", so the browser expects a PNG image rather than HTML. There is no reason to call those functions in the dashboard function, so just remove those...

Convert dictionary to object (or copy to local object var)

python,object,dictionary,web2py

class ObjectDict(dict): """ Object like dict, every dict[key] can be visited by dict.key """ def __getattr__(self, name): return self.__getitem__(name) ...

performance advantages of using bottle for routing?

python,performance,architecture,web2py,bottle

According to this benchmark and others, Bottle performs significantly faster than some of its peers, which is worth taking into account when comparing web frameworks' performance: 1. wheezy.web........52,245 req/sec or 19 μs/req (48x) 2. Falcon............30,195 req/sec or 33 μs/req (28x) 3. Bottle............11,977 req/sec or 83 μs/req (11x) 4. webpy..............6,950 req/sec...

Database field length is not enforced

python,sqlite3,web2py

SQLite is not like other databases. For all (most) practical purposes columns are untyped and INSERTs will always succeed and not lose data or precision (meaning, you can INSERT a text value into a REAL field if you want). The declared type of the column is used for a system...

Conditional statement using request.env.http_referer Web2py

web2py

{{if not request.env.http_referer.startswith( 'http://127.0.0.1:8000/test_wp/default/show_test/'):}} For more sophisticated pattern matching, you can of course use regular expressions....

Using isbntools with web2py

python,web2py,isbn

isbm_goom is a command line script. Is that what you want?! (you cannot use it in your code like that!) I suggests you use the most recent version of isbntools and adapt this snipet from isbntools.contrib.modules.goom import goom from isbntools.dev.fmt import fmtbib ... titledata = goom.query(form.vars.title) for r in titledata:...

web2py form with DB check [closed]

forms,validation,web2py

Assuming you wish to limit registration to a maximum of 20 users and you are using the standard /default/user function from the scaffolding application: In the default.py controller: def user(): if request.args(0) == 'register' and db.auth_user.count() >= 20: form = None else: form = auth() return dict(form=form) In the default/user.html...

web2py getting invalid function after adding new action to controller

python,web2py

Most likely the application has been bytecode compiled, so although you are changing the .py controller file, the .pyc compiled file is remaining unchanged. In the admin app, select "Remove compiled", and then re-compile the app with the new code.

Web2py with paramiko for ssh functionality

python,ssh,web2py,paramiko

Got the solution... I was using the compiled version of web2py. When i used the source code, importing of modules were not a head ache any more. Thank you Andrew Magee for giving a heads up...

How is it possible to use 'auth.navbar' for custom navigations?

python,web2py

Check out the auth.navbar signature. What you want can be achieved with this: {{=auth.navbar(separators=('', '', ''))}} You can also call auth.navbar(mode='bare'), which will return a dictionary with the relevant URLs and labels. You can then pass that dictionary to a custom navbar function to lay out and style the navbar...

What does 'times=X' in Web2py LOAD-helper?

web2py

For example you can use it together with timeout to show tweets about something, or last updates, or last messages... Something that is update continuously. This will call and show last_messages each 5 seconds. LOAD(c='default', f='last_messages', extension='load', target='mydiv', ajax=True, timeout=5000, times='infinity') ...

What is the use of Web2py's Field.Method?

python,web2py

It's basically a calculated db field. From the book: It is also possible to define method fields which are calculated on-demand, when called. For example: db.item.discounted_total = Field.Method(lambda row, discount=0.0: row.item.unit_pricerow.item.quantity(1.0-discount/100)) In this case row.discounted_total is not a value but a function. The function takes the same arguments as the...

Weird behavior with web2py DAL on table definition

database,web2py

Since db.customer is a keyed table (i.e., you have defined a primarykey attribute rather than relying on the default autoincrement integer ID field as the primary key), it can only be referenced by other keyed tables. Also, when creating reference fields for keyed tables, use the following syntax: Field('nric', 'reference...

How to pass raw data from controller into javascript?

javascript,python,web2py

data is already JSON, so no need for response.json -- just do: my_function({{=XML(data)}}) Alternatively, you can make data a Python object and use response.json to convert it to JSON: data = [{'value': 1, 'color': '#FF0000'}, {'value': 1, 'color': '#FF0000'}] ...

Is there a way to pass parameter for textarea-rows from database to html

python,web2py

Field('title', 'text', label=T('Please enter something:'), widget=lambda f, v: SQLFORM.widgets.text.widget(f, v, _rows=5)) For more details, see the relevant section in the documentation....

Auth user message when user is logged in Web2py

web2py

In the default layout.html, that is handled via auth.navbar(), which takes several options. Alternatively, you can just add the appropriate custom markup to your own template -- something like: {{='Welcome %s' % auth.user.first_name if auth.user else ''}} ...

Rendering HTML from a python String in web2py, generate @usename links python

javascript,jquery,python,html,web2py

For security, web2py templates will automatically escape any text inserted via {{=...}}. To disable the escaping, you can wrap the text in the XML() helper: {{=XML(link)}} ...

Web2py ajax function throwing index errors even when commented out or not called

jquery,ajax,comments,web2py,indexoutofboundsexception

In a web2py view file, any code in between the {{...}} delimiters is interpreted as Python code and executed on the server before returning the HTML to the browser. The code in question, vars={'actId':list[0]}, is Python code, so if the Python list is empty, list[0] will generate an exception. It...

calling jQuery on button click in web2py

jquery,web2py

A correct attribute selector is : $('[attributeName=NameValue]') Change jQuery('[data-direction=up]') Not jQuery('[data-direction=up') ...

web2py: Selecting distinct not null values from the database

web2py

You can use dictionary notation to reference table fields, using the field name as the key: db((db.task.workspace==270) & (db.task[col]!=None)).select(db.task[col], distinct=True) ...

How to use request.vars in web2py?

web2py

request.vars contains parameters passed in the body of an HTTP request (usually a GET or POST request derived from submitting a form). In your example, once you've defined x you could redirect from one to two while passing x in a variable called value: redirect(URL('two', vars=dict(value=x))) Then in two you...

Embedding pygal in web2py

web2py,pygal

It looks like pygal supports setting the size directly in the code: http://pygal.org/web/#iddirectly-in-the-html Alternatively you can override the width and height settings on the SVG element by using CSS: .svg-container svg { height: 240px; width: 240px; } NOTE: I'm using a class selector on the assumption that you might want...

web2py custom reset password

python,web2py,reset-password

the above code is working perfectly

Authentication with web2py on Google App Engine

python,google-app-engine,web2py

Yes, you can use the web2py Auth system on App Engine. The only limitation is that if you are using the Google Datastore, auth.accessible_query() won't work because it requires a join.

web2py displays id too

python,database,field,web2py

SQLFORM(db.base_folder, record=db.base_folder(1), showid=False) ...

How to pass generic keyword arguments and values to the update_record() function in web2py

python,web2py

You can use Python's keyword argument unpacking syntax (i.e., pass the arguments as a dictionary, which will be unpacked into keyword arguments and their values): db.my_table(content_id).update_record(**{field_name: request.vars[field_name]}) Actually, the table has a _filter_fields method that takes a dictionary-like object and filters it down to only the fields that belong in...

web2py serving zip file

zip,web2py,icalendar

You create only a single Calendar object outside of the for loop and then keep appending events to it. You should instead create a new Calendar object for each worker within the for loop: for i, rec in enumerate(grouped): cal = Calendar() ... ...

How can I select all items referenced by a specific list:reference field?

python,database,web2py

In this case, don't do a nested select. Instead, do a separate query to get the list of id's: item_ids = db.my_categories(slug=request.args[0]).items_ items = db(db.my_items.id.belongs(item_ids)).select() ...

web2py: SQLFORM URL duplicate validation

web2py

You could create a custom validator to strip the http/https before further processing: import re db.url.URL.requires = [lambda url: (re.sub(r'http[s]?://', '', url), None), IS_URL(error_message='URL Error'), IS_NOT_IN_DB(db, 'url.URL',error_message='Dupilcated URL')] Note, the custom validator returns a tuple including the altered URL and None (the None indicates that there is no error). That...

Web2Py DAL - How to check list:string type items for None

python,web2py,data-access-layer

If you input records via SQLFORM, empty values for task will get stored as an empty list rather than None, so you can do: db(db.newItems.tasks != []).select(db.newItems.tasks) Note, that will also exclude records that happen to have None values for task (which might exist if you have inserted records without...

Does web2py ajax() function really work with onchange event of ?

html,ajax,forms,file-upload,web2py

Your code is attempting to send the whole file via Ajax rather than just sending the filename. To send just the filename, don't use the second argument of the ajax() function, but instead add the filename to the query string of the Ajax URL: <form>File to upload: <input name="zefilename" type="file"...