[web2py] Multiselect form and many-to-many relationship

2012-04-14 Thread Chris Rowson
Hi all,

I'm pretty new to web2py and web app development and I've spend some time
trying to figure out the best way to do this.

I have two tables, house-types and regions. A house-type can exist in many
regions, and a region can have many house types:

db.define_table(
'region',
Field('name', 'string', length=512, required=True),
format = '%(name)s')

db.define_table(
'house-type',
Field('title', 'string', length=512), #title of the newbuild property
listing
Field('vendor',db.vendor, required=True),
Field('bedrooms', 'integer'),
Field('price', 'double',required=True),
Field('description', 'text',length=65536, required=True),
Field('live', 'boolean', default=False)
)

If I understand correctly, in order to create the many-to-many relationship
I should create a junction table like the following:

db.define_table(
   'houses_and_regions',
   Field('house', db.house-type),
   Field('region', db.region))

And then I should use SQLFORM to construct a form which updates both
house-type and houses_and_region tables when I create or modify a new house.

What I'm struggling with is how to create a form which allows me to select
multiple regions for a house. I wondered if anyone could give me any
examples?

Thanks in advance!

Chris


Re: [web2py] Re: Multiselect form and many-to-many relationship

2012-04-14 Thread Chris Rowson
Hi David,

Thanks for your reply.

I did come across the list:reference option while trying to figure this
out. I couldn't figure this out though:

Say I add the following to my house-type table:

   Field('regions', 'list:reference region')

If I generate a form using SQLFORM, it presents me with a multiselect
region option where I can select as many regions as I need. Reading around,
it seems that the region field would then store something like this for
instance:

   'england', 'france', 'US', 'china'

How do I then create a query to show all house-type records with a region
of 'china' for instance?

I'm not an experienced user of development frameworks like this. Is it
usually this difficult to accomplish this kind of thing? Seems to me it
would be a pretty common requirement?

Thanks in advance, :-)

Chris

On Sat, Apr 14, 2012 at 8:52 PM, villas  wrote:

> I would just mention that if you only have a few regions/housetypes,  you
> might consider de-normalising the data and using list:reference and work
> with the jQuery.multiselect (if you have any problems with that,  you might
> like to read my other thread on the topic).
> Best regards,  David
>
> On Saturday, 14 April 2012 18:31:58 UTC+1, leftcase wrote:
>>
>> Hi all,
>>
>> I'm pretty new to web2py and web app development and I've spend some time
>> trying to figure out the best way to do this.
>>
>> I have two tables, house-types and regions. A house-type can exist in
>> many regions, and a region can have many house types:
>>
>> db.define_table(
>> 'region',
>> Field('name', 'string', length=512, required=True),
>> format = '%(name)s')
>>
>> db.define_table(
>> 'house-type',
>> Field('title', 'string', length=512), #title of the newbuild property
>> listing
>> Field('vendor',db.vendor, required=True),
>> Field('bedrooms', 'integer'),
>> Field('price', 'double',required=True),
>> Field('description', 'text',length=65536, required=True),
>> Field('live', 'boolean', default=False)
>> )
>>
>> If I understand correctly, in order to create the many-to-many
>> relationship I should create a junction table like the following:
>>
>> db.define_table(
>>'houses_and_regions',
>>Field('house', db.house-type),
>>Field('region', db.region))
>>
>> And then I should use SQLFORM to construct a form which updates both
>> house-type and houses_and_region tables when I create or modify a new house.
>>
>> What I'm struggling with is how to create a form which allows me to
>> select multiple regions for a house. I wondered if anyone could give me any
>> examples?
>>
>> Thanks in advance!
>>
>> Chris
>>
>


Re: [web2py] Re: Multiselect form and many-to-many relationship

2012-04-14 Thread Chris Rowson
Thank you again David,

I shall give it a go.

Chris

On Sat, Apr 14, 2012 at 10:29 PM, villas  wrote:

> Yes,  it would store the ids of the regions between vertical bars,
> something like this: |4|7|23|.  So say you are looking for the house-types
> in China (which is id = 7).  It would be something like this:
>
> if you already have the record id no.7,  then just this:
> houses = db(db.house_types.regions.contains('|7|')).select()
>
> Or, you might have the find the record no. first:
> china_rec = db(db.regions.name == 'China').select(db.regions.id).first()
> houses = db(db.house_types.regions.contains('|'+str(china_rec.id
> )+'|')).select()
>
> As long as your requirements are not too complex it seems to work well.
>  See also the book.  DAL chapter, search for list:reference.
>
> Regards, D
>
> On Saturday, 14 April 2012 21:27:34 UTC+1, leftcase wrote:
>
>> Hi David,
>>
>> Thanks for your reply.
>>
>> I did come across the list:reference option while trying to figure this
>> out. I couldn't figure this out though:
>>
>> Say I add the following to my house-type table:
>>
>>Field('regions', 'list:reference region')
>>
>> If I generate a form using SQLFORM, it presents me with a multiselect
>> region option where I can select as many regions as I need. Reading around,
>> it seems that the region field would then store something like this for
>> instance:
>>
>>'england', 'france', 'US', 'china'
>>
>> How do I then create a query to show all house-type records with a region
>> of 'china' for instance?
>>
>> I'm not an experienced user of development frameworks like this. Is it
>> usually this difficult to accomplish this kind of thing? Seems to me it
>> would be a pretty common requirement?
>>
>> Thanks in advance, :-)
>>
>> Chris
>>
>> On Sat, Apr 14, 2012 at 8:52 PM, villas wrote:
>>
>>> I would just mention that if you only have a few regions/housetypes,
>>>  you might consider de-normalising the data and using list:reference and
>>> work with the jQuery.multiselect (if you have any problems with that,  you
>>> might like to read my other thread on the topic).
>>> Best regards,  David
>>>
>>> On Saturday, 14 April 2012 18:31:58 UTC+1, leftcase wrote:

 Hi all,

 I'm pretty new to web2py and web app development and I've spend some
 time trying to figure out the best way to do this.

 I have two tables, house-types and regions. A house-type can exist in
 many regions, and a region can have many house types:

 db.define_table(
 'region',
 Field('name', 'string', length=512, required=True),
 format = '%(name)s')

 db.define_table(
 'house-type',
 Field('title', 'string', length=512), #title of the newbuild
 property listing
 Field('vendor',db.vendor, required=True),
 Field('bedrooms', 'integer'),
 Field('price', 'double',required=True),
 Field('description', 'text',length=65536, required=True),
 Field('live', 'boolean', default=False)
 )

 If I understand correctly, in order to create the many-to-many
 relationship I should create a junction table like the following:

 db.define_table(
'houses_and_regions',
Field('house', db.house-type),
Field('region', db.region))

 And then I should use SQLFORM to construct a form which updates both
 house-type and houses_and_region tables when I create or modify a new 
 house.

 What I'm struggling with is how to create a form which allows me to
 select multiple regions for a house. I wondered if anyone could give me any
 examples?

 Thanks in advance!

 Chris

>>>
>>


Re: [web2py] Re: Multiselect form and many-to-many relationship

2012-04-15 Thread Chris Rowson
Heh, no worries. :-)

I wonder, just out of interest, is there any great performance difference
between searching for records containing region.id 'x' (as below) rather
than returning all rows with region.id 'x' from a junction table?

Chris

On Sat, Apr 14, 2012 at 11:34 PM, villas  wrote:

> Oops I think I got confused with the vertical bars,  try it with just a
> plain integer:
> houses = db(db.house_types.regions.**contains(7)).select()
>
>
> On Saturday, 14 April 2012 22:33:54 UTC+1, leftcase wrote:
>
>> Thank you again David,
>>
>> I shall give it a go.
>>
>> Chris
>>
>>
>> On Sat, Apr 14, 2012 at 10:29 PM, villas wrote:
>>
>>> Yes,  it would store the ids of the regions between vertical bars,
>>> something like this: |4|7|23|.  So say you are looking for the house-types
>>> in China (which is id = 7).  It would be something like this:
>>>
>>> if you already have the record id no.7,  then just this:
>>> houses = db(db.house_types.regions.**contains('|7|')).select()
>>>
>>> Or, you might have the find the record no. first:
>>> china_rec = db(db.regions.name == 'China').select(db.regions.id)**
>>> .first()
>>> houses = db(db.house_types.regions.**contains('|'+str(china_rec.id)**
>>> +'|')).select()
>>>
>>> As long as your requirements are not too complex it seems to work well.
>>>  See also the book.  DAL chapter, search for list:reference.
>>>
>>> Regards, D
>>>
>>> On Saturday, 14 April 2012 21:27:34 UTC+1, leftcase wrote:
>>>
 Hi David,

 Thanks for your reply.

 I did come across the list:reference option while trying to figure this
 out. I couldn't figure this out though:

 Say I add the following to my house-type table:

Field('regions', 'list:reference region')

 If I generate a form using SQLFORM, it presents me with a multiselect
 region option where I can select as many regions as I need. Reading around,
 it seems that the region field would then store something like this for
 instance:

'england', 'france', 'US', 'china'

 How do I then create a query to show all house-type records with a
 region of 'china' for instance?

 I'm not an experienced user of development frameworks like this. Is it
 usually this difficult to accomplish this kind of thing? Seems to me it
 would be a pretty common requirement?

 Thanks in advance, :-)

 Chris

 On Sat, Apr 14, 2012 at 8:52 PM, villas wrote:

> I would just mention that if you only have a few regions/housetypes,
>  you might consider de-normalising the data and using list:reference and
> work with the jQuery.multiselect (if you have any problems with that,  you
> might like to read my other thread on the topic).
> Best regards,  David
>
> On Saturday, 14 April 2012 18:31:58 UTC+1, leftcase wrote:
>>
>> Hi all,
>>
>> I'm pretty new to web2py and web app development and I've spend some
>> time trying to figure out the best way to do this.
>>
>> I have two tables, house-types and regions. A house-type can exist in
>> many regions, and a region can have many house types:
>>
>> db.define_table(
>> 'region',
>> Field('name', 'string', length=512, required=True),
>> format = '%(name)s')
>>
>> db.define_table(
>> 'house-type',
>> Field('title', 'string', length=512), #title of the newbuild
>> property listing
>> Field('vendor',db.vendor, required=True),
>> Field('bedrooms', 'integer'),
>> Field('price', 'double',required=True),
>> Field('description', 'text',length=65536, required=True),
>> Field('live', 'boolean', default=False)
>> )
>>
>> If I understand correctly, in order to create the many-to-many
>> relationship I should create a junction table like the following:
>>
>> db.define_table(
>>'houses_and_regions',
>>Field('house', db.house-type),
>>Field('region', db.region))
>>
>> And then I should use SQLFORM to construct a form which updates both
>> house-type and houses_and_region tables when I create or modify a new 
>> house.
>>
>> What I'm struggling with is how to create a form which allows me to
>> select multiple regions for a house. I wondered if anyone could give me 
>> any
>> examples?
>>
>> Thanks in advance!
>>
>> Chris
>>
>

>>


[web2py] Database design

2012-04-17 Thread Chris Rowson
I'm a new adopter of web2py and I'm trying to learn the framework by
building a simple property site.

I have two types of properties, new or old.

New properties have a few core attributes, let's say name, price, location,
bedrooms

Old properties have the same core attributes with a few more added on, for
instance utilities, land, lease type.

I've tried making a table for new properties and a table for old properties
but it seems to complicate things if I for instance want to list all types
of properties (new and old) and order by price (I've been struggling to
figure out how to aggregate the results from both tables then order by
price).

Would it make more sense to have one table with all of the fields for new
and old properties and simply create two different forms with different
fields exposed depending on whether or not the user wants to create a new
or an old property?

Thanks in advance,

Chris


Re: [web2py] Re: Database design

2012-04-18 Thread Chris Rowson
Thanks for confirming this for me, this did seem to be the most sensible
way to approach the problem :-)

Chris

On Wed, Apr 18, 2012 at 1:04 AM, simon  wrote:

> You can do this with a single form. At the top of the controller set
> readable=false,  writable=false for the fields you do not want on the form.
>
> On Tuesday, 17 April 2012 23:44:54 UTC+1, leftcase wrote:
>
>> I'm a new adopter of web2py and I'm trying to learn the framework by
>> building a simple property site.
>>
>> I have two types of properties, new or old.
>>
>> New properties have a few core attributes, let's say name, price,
>> location, bedrooms
>>
>> Old properties have the same core attributes with a few more added on,
>> for instance utilities, land, lease type.
>>
>> I've tried making a table for new properties and a table for old
>> properties but it seems to complicate things if I for instance want to list
>> all types of properties (new and old) and order by price (I've been
>> struggling to figure out how to aggregate the results from both tables then
>> order by price).
>>
>> Would it make more sense to have one table with all of the fields for new
>> and old properties and simply create two different forms with different
>> fields exposed depending on whether or not the user wants to create a new
>> or an old property?
>>
>> Thanks in advance,
>>
>> Chris
>>
>


Re: [web2py] Re: Database design

2012-04-18 Thread Chris Rowson
I've put this into the controller to test this out:

def create_newbuild():
#newbuild and resale properties share the same table.
#the extraneous fields are rendered non-writable by the below
db.property.land.writable = False
db.property.reference_number.writable = False
db.property.habitable_area.writable = False
db.property.utilities.writable = False
db.property.address.writable = False
db.property.postcode.writable = False
db.property.land.readable = False
db.property.reference_number.readable = False
db.property.habitable_area.readable = False
db.property.utilities.readable = False
db.property.address.readable = False
db.property.postcode.readable = False
db.property.property_type.default="2" #select the newbuild property
type and hide the option from the user
db.property.property_type.readable = False
form=SQLFORM(db.property)
if form.process().accepted:
response.flash = 'form accepted'
elif form.errors:
response.flash = 'form has errors'
else:
response.flash = 'please fill out the form'
return dict(form=form)

Strange thing is though that the property_type field still appears on the
form. Any ideas why?

Thank you,

Chris

On Wed, Apr 18, 2012 at 3:43 PM, Chris Rowson
wrote:

> Thanks for confirming this for me, this did seem to be the most sensible
> way to approach the problem :-)
>
> Chris
>
>
> On Wed, Apr 18, 2012 at 1:04 AM, simon  wrote:
>
>> You can do this with a single form. At the top of the controller set
>> readable=false,  writable=false for the fields you do not want on the form.
>>
>> On Tuesday, 17 April 2012 23:44:54 UTC+1, leftcase wrote:
>>
>>> I'm a new adopter of web2py and I'm trying to learn the framework by
>>> building a simple property site.
>>>
>>> I have two types of properties, new or old.
>>>
>>> New properties have a few core attributes, let's say name, price,
>>> location, bedrooms
>>>
>>> Old properties have the same core attributes with a few more added on,
>>> for instance utilities, land, lease type.
>>>
>>> I've tried making a table for new properties and a table for old
>>> properties but it seems to complicate things if I for instance want to list
>>> all types of properties (new and old) and order by price (I've been
>>> struggling to figure out how to aggregate the results from both tables then
>>> order by price).
>>>
>>> Would it make more sense to have one table with all of the fields for
>>> new and old properties and simply create two different forms with different
>>> fields exposed depending on whether or not the user wants to create a new
>>> or an old property?
>>>
>>> Thanks in advance,
>>>
>>> Chris
>>>
>>
>


Re: [web2py] Re: Database design

2012-04-19 Thread Chris Rowson
Of course, silly me. Couldn't see the trees for the forest :-) Thank you
Anthony.

Chris

On Thu, Apr 19, 2012 at 1:20 AM, Anthony  wrote:

> db.property.property_type.writable = False
>
> Anthony
>
>
> On Wednesday, April 18, 2012 4:32:02 PM UTC-4, leftcase wrote:
>>
>> I've put this into the controller to test this out:
>>
>> def create_newbuild():
>> #newbuild and resale properties share the same table.
>> #the extraneous fields are rendered non-writable by the below
>> db.property.land.writable = False
>> db.property.reference_number.**writable = False
>> db.property.habitable_area.**writable = False
>> db.property.utilities.writable = False
>> db.property.address.writable = False
>> db.property.postcode.writable = False
>> db.property.land.readable = False
>> db.property.reference_number.**readable = False
>> db.property.habitable_area.**readable = False
>> db.property.utilities.readable = False
>> db.property.address.readable = False
>> db.property.postcode.readable = False
>> db.property.property_type.**default="2" #select the newbuild
>> property type and hide the option from the user
>> db.property.property_type.**readable = False
>> form=SQLFORM(db.property)
>> if form.process().accepted:
>> response.flash = 'form accepted'
>> elif form.errors:
>> response.flash = 'form has errors'
>> else:
>> response.flash = 'please fill out the form'
>> return dict(form=form)
>>
>> Strange thing is though that the property_type field still appears on the
>> form. Any ideas why?
>>
>> Thank you,
>>
>> Chris
>>
>> On Wed, Apr 18, 2012 at 3:43 PM, Chris Rowson <
>> christopherrow...@gmail.com> wrote:
>>
>>> Thanks for confirming this for me, this did seem to be the most sensible
>>> way to approach the problem :-)
>>>
>>> Chris
>>>
>>>
>>> On Wed, Apr 18, 2012 at 1:04 AM, simon  wrote:
>>>
>>>> You can do this with a single form. At the top of the controller set
>>>> readable=false,  writable=false for the fields you do not want on the form.
>>>>
>>>> On Tuesday, 17 April 2012 23:44:54 UTC+1, leftcase wrote:
>>>>
>>>>> I'm a new adopter of web2py and I'm trying to learn the framework by
>>>>> building a simple property site.
>>>>>
>>>>> I have two types of properties, new or old.
>>>>>
>>>>> New properties have a few core attributes, let's say name, price,
>>>>> location, bedrooms
>>>>>
>>>>> Old properties have the same core attributes with a few more added on,
>>>>> for instance utilities, land, lease type.
>>>>>
>>>>> I've tried making a table for new properties and a table for old
>>>>> properties but it seems to complicate things if I for instance want to 
>>>>> list
>>>>> all types of properties (new and old) and order by price (I've been
>>>>> struggling to figure out how to aggregate the results from both tables 
>>>>> then
>>>>> order by price).
>>>>>
>>>>> Would it make more sense to have one table with all of the fields for
>>>>> new and old properties and simply create two different forms with 
>>>>> different
>>>>> fields exposed depending on whether or not the user wants to create a new
>>>>> or an old property?
>>>>>
>>>>> Thanks in advance,
>>>>>
>>>>> Chris
>>>>>
>>>>
>>>
>>


Re: [web2py] Re: has anyone done web2py + google maps?

2011-09-10 Thread Chris Rowson
I'm a Python Web Dev noob, but I had a similar requirement. I created
this function to convert a postcode into lon & lat data suitable for
use in Google Maps. It's a work in progress, not very elegant, and it
doesn't have any error management but it's a start. Hopefully someone
on the list will be able to point out any serious problems with it if
there are any ;-)

import urllib
import xml.dom.minidom
"""Returns latitude and longitude when passed a postcode
"""
geocodeUrl='http://maps.googleapis.com/maps/api/geocode/xml?address='
sensor='&sensor=false'
#send the postcode to Google for geocoding
dom=xml.dom.minidom.parse(urllib.urlopen(geocodeUrl+address+sensor))

#grab the location element
location=dom.getElementsByTagName('location')[0]

#pull out the lat & lng elements and remove the  &  tags

lat=location.getElementsByTagName('lat')[0].toxml().replace('','').replace('','')

lng=location.getElementsByTagName('lng')[0].toxml().replace('','').replace('','')

georesults = {'lat':lat, 'lng':lng}

return georesults


[web2py] Computing a field from the value of another field

2011-09-10 Thread Chris Rowson
Hi there,

I bought the web2py .pdf, and have been reading it, but I'm struggling
a little bit with:

http://www.web2py.com/book/default/chapter/07#SQLFORM

Specifically the section "SQLFORM without database IO"

I have 2 fields, lon & lat I'd like to calculated from a postcode and
enter into the database. I want this to happen automatically, I don't
want the user to see them in the form.

As you can see below, I've done this by setting dbio=False, computing
the fields from the postcode value then adding them to the forms.var
dict before submitting it all together. Is this a rational way to
accomplish my requirements?

Thanks in advance!

Chris

def adddata():
form=SQLFORM(db.data, fields=['provider', 'speed', 'postcode', 'ping'])
if form.accepts(request.vars, session, dbio=False): #<-- dbio
false means it doesn't submit till we ask it to
   geocoded=__geocode(form.vars.postcode) #<-- so compute the other fields
   #add some computed values to the form.vars dictionary for submission
   form.vars['lon']=geocoded['lon']
   form.vars['lat']=geocoded['lat']
   #and insert the data into the database
   db.data.insert(**dict(form.vars))
   #response.flash puts the flash in this page, session.flash in
the next page of the session
   session.flash = 'form accepted'
   redirect(URL(r=request, f='index'))
elif form.errors:
   response.flash = 'form has errors'
return dict(form=form)


[web2py] Re: Computing a field from the value of another field

2011-09-10 Thread Chris Rowson
> Hi there,
>
> I bought the web2py .pdf, and have been reading it, but I'm struggling
> a little bit with:
>
> http://www.web2py.com/book/default/chapter/07#SQLFORM
>
> Specifically the section "SQLFORM without database IO"
>
> I have 2 fields, lon & lat I'd like to calculated from a postcode and
> enter into the database. I want this to happen automatically, I don't
> want the user to see them in the form.
>
> As you can see below, I've done this by setting dbio=False, computing
> the fields from the postcode value then adding them to the forms.var
> dict before submitting it all together. Is this a rational way to
> accomplish my requirements?
>
> Thanks in advance!
>
> Chris
>
> def adddata():
>    form=SQLFORM(db.data, fields=['provider', 'speed', 'postcode', 'ping'])
>    if form.accepts(request.vars, session, dbio=False): #<-- dbio
> false means it doesn't submit till we ask it to
>       geocoded=__geocode(form.vars.postcode) #<-- so compute the other fields
>       #add some computed values to the form.vars dictionary for submission
>       form.vars['lng']=geocoded['lng']
>       form.vars['lat']=geocoded['lat']
>       #and insert the data into the database
>       db.data.insert(**dict(form.vars))
>       #response.flash puts the flash in this page, session.flash in
> the next page of the session
>       session.flash = 'form accepted'
>       redirect(URL(r=request, f='index'))
>    elif form.errors:
>       response.flash = 'form has errors'
>    return dict(form=form)
>

It might also help to show you the geocode function (changed lon to lng too)

def __geocode(address):
import urllib
import xml.dom.minidom
"""Returns latitude and longitude when passed a postcode
"""
geocodeUrl='http://maps.googleapis.com/maps/api/geocode/xml?address='
sensor='&sensor=false'
#send the postcode to Google for geocoding
dom=xml.dom.minidom.parse(urllib.urlopen(geocodeUrl+address+sensor))

#grab the location element
location=dom.getElementsByTagName('location')[0]

#pull out the lat & lng elements and remove the  &  tags

lat=location.getElementsByTagName('lat')[0].toxml().replace('','').replace('','')

lng=location.getElementsByTagName('lng')[0].toxml().replace('','').replace('','')

georesults = {'lat':lat, 'lng':lng}

return georesults


Re: [web2py] Re: Computing a field from the value of another field

2011-09-10 Thread Chris Rowson
Cool, Thanks Anthony!

Does the onvalidation option have benefits over and above the way I've done it?

Chris

> Another option might be using an onvalidation function:
> http://web2py.com/book/default/chapter/07#onvalidation
> Anthony
>
> On Saturday, September 10, 2011 4:37:08 PM UTC-4, leftcase wrote:
>>
>> Hi there,
>>
>> I bought the web2py .pdf, and have been reading it, but I'm struggling
>> a little bit with:
>>
>> http://www.web2py.com/book/default/chapter/07#SQLFORM
>>
>> Specifically the section "SQLFORM without database IO"
>>
>> I have 2 fields, lon & lat I'd like to calculated from a postcode and
>> enter into the database. I want this to happen automatically, I don't
>> want the user to see them in the form.
>>
>> As you can see below, I've done this by setting dbio=False, computing
>> the fields from the postcode value then adding them to the forms.var
>> dict before submitting it all together. Is this a rational way to
>> accomplish my requirements?
>>
>> Thanks in advance!
>>
>> Chris
>>
>> def adddata():
>>     form=SQLFORM(db.data, fields=['provider', 'speed', 'postcode',
>> 'ping'])
>>     if form.accepts(request.vars, session, dbio=False): #<-- dbio
>> false means it doesn't submit till we ask it to
>>        geocoded=__geocode(form.vars.postcode) #<-- so compute the other
>> fields
>>        #add some computed values to the form.vars dictionary for
>> submission
>>        form.vars['lon']=geocoded['lon']
>>        form.vars['lat']=geocoded['lat']
>>        #and insert the data into the database
>>        db.data.insert(**dict(form.vars))
>>        #response.flash puts the flash in this page, session.flash in
>> the next page of the session
>>        session.flash = 'form accepted'
>>        redirect(URL(r=request, f='index'))
>>     elif form.errors:
>>        response.flash = 'form has errors'
>>     return dict(form=form)
>


Re: [web2py] Re: Computing a field from the value of another field

2011-09-11 Thread Chris Rowson
Thank you everyone for the advice.

Chris
On Sep 11, 2011 4:47 AM, "pbreit"  wrote:
> Good point.


[web2py] Selecting a linked field

2011-09-12 Thread Chris Rowson
I have two tables:
-
db.define_table('providers',
   Field('name'),
   Field('email'),
   Field('tel')

db.define_table('data',
   Field('dataowner', db.auth_user, default=auth.user_id,
writable=False, readable=False), #this points at the auth user
   Field('provider', db.providers),
   Field('speed', 'integer')

db.data.provider.requires=IS_IN_DB(db, 'providers.id','providers.name')
-

My controller has this code

def map():
response.view="map.html"
# selects the data postcode fields from the database
# returns an interable object
rows=db().select(db.data.lon, db.data.lat, db.data.provider)
return dict(rows=rows)

---

And my view this code

 {{for i,row in enumerate(rows):}}{{if not i==0:}},{{pass}}
  { lat: {{=row.lat}}, lng: {{=row.lon}}, name: "{{=row.provider.name}}" }
  {{pass}}


As you can see, the provider field in the data table stores the provider id.

I'm confused!

Although this does work I don't know why!, is it the correct way to
reference the name field from the providers table?

Thanks!

Chris


Re: [web2py] Re: Selecting a linked field

2011-09-12 Thread Chris Rowson
Thank you both. I shall revisit, replace with a join and put the logic
into the controller rather than the view :-)

Chris


Re: [web2py] Re: Selecting a linked field

2011-09-13 Thread Chris Rowson
Started to rework this. Changed to an inner join (I believe!) as suggested.

rows=db(db.data.provider==db.providers.id).select(db.data.lon,
db.data.lat, db.providers.name)

Chris

On Mon, Sep 12, 2011 at 9:54 PM, Chris Rowson
 wrote:
> Thank you both. I shall revisit, replace with a join and put the logic
> into the controller rather than the view :-)
>
> Chris
>


Re: [web2py] Re: Why web2py is in French by default? How can I change it?

2011-09-15 Thread Chris Rowson
I had the same problem the other day. Then it reverted itself again.

Chris

On Thu, Sep 15, 2011 at 12:50 PM, kenji4569  wrote:
> I met exactly the same problem. My browser is set with Japanese and
> has nothing to do with French settings.
>
> Regards,
> Kenji
>
> On 9月15日, 午後7:10, guruyaya  wrote:
>> I think your browser is set with french by default. Look into your
>> browser settings.
>>
>> On Sep 15, 11:08 am, Zhe Li  wrote:
>>
>>
>>
>>
>>
>>
>>
>> > Hi,
>>
>> > I tried to find something in web2py book, but everything is in French now.
>> > (Wasn't like this yesterday)
>>
>> > I am sure I have set my browser to English, anything wrong?
>>
>> > Cheers,
>> > Zhe
>


[web2py] Data stored in memory

2011-09-17 Thread Chris Rowson
Hi folks,

I'm trying to get my head around what happens to data stored in memory when
it isn't needed anymore.

Let me give you an example. Let's say I create a function which returns a
dict called 'results' populated with data from an external source each time
a user registers (for instance let's say it has data returned from geocoding
the users postcode and providing info about the area).

So the 'results' dict holds that data, it is used, and then what? Is the
memory automatically freed up again when we finish with the data or does it
hang around in memory?

I'm pretty new to python and web2py, can anyone help me understand?

Thank you!

Chris


Re: [web2py] Data stored in memory

2011-09-17 Thread Chris Rowson
I had read a little about that already, but found myself a little confused
as to when an object does or does not continue to refer to another object as
described in reference counts. At least you've confirmed I'm on the right
track. I'll go back to the books.

Thank-you

Chris
On Sep 17, 2011 2:08 PM, "Vasile Ermicioi"  wrote:
> google for python garbage collection


Re: [web2py] Re: Data stored in memory

2011-09-19 Thread Chris Rowson
Thank you all.

I think I get the gist of what happens now.

Really appreciating all of the effort you guys put into helping people
on this list!

Chris

On Sat, Sep 17, 2011 at 4:17 PM, Anthony  wrote:
> Also, note that your 'results' dict will only persist for the duration of a
> single request. Each request is handled by a new thread (from a thread
> pool).
> Anthony
>
> On Saturday, September 17, 2011 11:06:14 AM UTC-4, Massimo Di Pierro wrote:
>>
>> On Sep 17, 6:31 am, Chris Rowson  wrote:
>> > Hi folks,
>> >
>> > I'm trying to get my head around what happens to data stored in memory
>> > when
>> > it isn't needed anymore.
>> >
>> > Let me give you an example. Let's say I create a function which returns
>> > a
>> > dict called 'results' populated with data from an external source each
>> > time
>> > a user registers (for instance let's say it has data returned from
>> > geocoding
>> > the users postcode and providing info about the area).
>> >
>> > So the 'results' dict holds that data, it is used, and then what? Is the
>> > memory automatically freed up again when we finish with the data or does
>> > it
>> > hang around in memory?
>>
>> Yes. Python uses reference counting. Every variable is a pointer to a
>> memory location. It keeps tracks of how many pointers point to the
>> same location.
>>
>> a = A() # one pointer
>> b = a # two pointers
>> c = a # three pointers
>>
>> when you delete one the counter is decreased
>>
>> b = 4 # now two variables (a,c) point to A()
>>
>> when the counter is zero the object is freed.
>>
>> This works great UNLESS the objects have circular references (a.x=a)
>> AND the object has a destructor (A.__del__). As long a you do not use
>> destructors (who needs them?) everything works great.
>>
>>
>>
>>
>


[web2py] xml.etree

2011-09-19 Thread Chris Rowson
Anybody using xml.etree?

I asked this question over at the Python tutors group but it seems
that few people there had experience of it.

I'm trying to access a UK postcode API at www.uk-postcodes.com to take
a UK postcode and return the lat/lng of the postcode. This is what the
XML looks like: http://www.uk-postcodes.com/postcode/HU11AA.xml

The function below returns a dict with the xml tag as a key and the
text as a value. Is this a correct way to use xml.etree? Is there a
better way of doing this?

Thanks in advance!

Chris


def ukpostcodesapi(postcode):
   import urllib
   import xml.etree.ElementTree as etree

   baseURL='http://www.uk-postcodes.com/'
   geocodeRequest='postcode/'+postcode+'.xml'

   #grab the xml
   tree=etree.parse(urllib.urlopen(baseURL+geocodeRequest))
   root=tree.getroot()
   results={}
   for child in root[1]: #here's the geo tag
   results.update({child.tag:child.text}) #build a dict
containing the geocode data
   return results

#example usage (testing the function)
results = ukpostcodesapi('hu11aa')
print results['lat']+' '+results['lng']


Re: [web2py] xml.etree

2011-09-19 Thread Chris Rowson
Thank you Michele,

Chris

On Mon, Sep 19, 2011 at 2:00 PM, Michele Comitini
 wrote:
> There is nothing wrong with your code. Maybe it is better to use
> find() to get the  tag.
> If you have an XSD schema you can use generateDS
> http://www.rexx.com/~dkuhlman/generateDS.html
> to have a python parser.
>
> But if you can use the JSON API... much simpler.
>
> mic
>
>
> 2011/9/19 Chris Rowson :
>> Anybody using xml.etree?
>>
>> I asked this question over at the Python tutors group but it seems
>> that few people there had experience of it.
>>
>> I'm trying to access a UK postcode API at www.uk-postcodes.com to take
>> a UK postcode and return the lat/lng of the postcode. This is what the
>> XML looks like: http://www.uk-postcodes.com/postcode/HU11AA.xml
>>
>> The function below returns a dict with the xml tag as a key and the
>> text as a value. Is this a correct way to use xml.etree? Is there a
>> better way of doing this?
>>
>> Thanks in advance!
>>
>> Chris
>>
>>
>> def ukpostcodesapi(postcode):
>>       import urllib
>>       import xml.etree.ElementTree as etree
>>
>>       baseURL='http://www.uk-postcodes.com/'
>>       geocodeRequest='postcode/'+postcode+'.xml'
>>
>>       #grab the xml
>>       tree=etree.parse(urllib.urlopen(baseURL+geocodeRequest))
>>       root=tree.getroot()
>>       results={}
>>       for child in root[1]: #here's the geo tag
>>               results.update({child.tag:child.text}) #build a dict
>> containing the geocode data
>>       return results
>>
>> #example usage (testing the function)
>> results = ukpostcodesapi('hu11aa')
>> print results['lat']+' '+results['lng']
>>
>


Re: [web2py] xml.etree

2011-09-19 Thread Chris Rowson
I did look at that Bruno, but some of the articles I read suggested that it
is not very memory efficient?

Chris
On Sep 19, 2011 3:44 PM, "Bruno Rocha"  wrote:
> I use xml minidom and it is easier.
>
> http://zerp.ly/rochacbruno
> Em 19/09/2011 11:40, "Chris Rowson" 
escreveu:
>> Thank you Michele,
>>
>> Chris
>>
>> On Mon, Sep 19, 2011 at 2:00 PM, Michele Comitini
>>  wrote:
>>> There is nothing wrong with your code. Maybe it is better to use
>>> find() to get the  tag.
>>> If you have an XSD schema you can use generateDS
>>> http://www.rexx.com/~dkuhlman/generateDS.html
>>> to have a python parser.
>>>
>>> But if you can use the JSON API... much simpler.
>>>
>>> mic
>>>
>>>
>>> 2011/9/19 Chris Rowson :
>>>> Anybody using xml.etree?
>>>>
>>>> I asked this question over at the Python tutors group but it seems
>>>> that few people there had experience of it.
>>>>
>>>> I'm trying to access a UK postcode API at www.uk-postcodes.com to take
>>>> a UK postcode and return the lat/lng of the postcode. This is what the
>>>> XML looks like: http://www.uk-postcodes.com/postcode/HU11AA.xml
>>>>
>>>> The function below returns a dict with the xml tag as a key and the
>>>> text as a value. Is this a correct way to use xml.etree? Is there a
>>>> better way of doing this?
>>>>
>>>> Thanks in advance!
>>>>
>>>> Chris
>>>>
>>>>
>>>> def ukpostcodesapi(postcode):
>>>> import urllib
>>>> import xml.etree.ElementTree as etree
>>>>
>>>> baseURL='http://www.uk-postcodes.com/'
>>>> geocodeRequest='postcode/'+postcode+'.xml'
>>>>
>>>> #grab the xml
>>>> tree=etree.parse(urllib.urlopen(baseURL+geocodeRequest))
>>>> root=tree.getroot()
>>>> results={}
>>>> for child in root[1]: #here's the geo tag
>>>> results.update({child.tag:child.text}) #build a dict
>>>> containing the geocode data
>>>> return results
>>>>
>>>> #example usage (testing the function)
>>>> results = ukpostcodesapi('hu11aa')
>>>> print results['lat']+' '+results['lng']
>>>>
>>>


Re: [web2py] xml.etree

2011-09-19 Thread Chris Rowson
Thanks all!

Chris

On Mon, Sep 19, 2011 at 6:49 PM, Phyo Arkar  wrote:
> I like lxml more , and check pyquery! jQuery of python at server side.
>
> On 9/20/11, Bruno Rocha  wrote:
>> I dont know your needs but, you can pass any XML to web2py TAG[''] helper so
>> then you can use Server side DOM to inspect
>>
>> http://web2py.com/book/default/chapter/05#Server-side-DOM-and-Parsing
>>
>


Re: [web2py] xml.etree

2011-09-19 Thread Chris Rowson
 I ended up with something like this:

http://pastebin.com/Y9keC9tB

Chris

On Mon, Sep 19, 2011 at 8:42 PM, Chris Rowson
 wrote:
> Thanks all!
>
> Chris
>
> On Mon, Sep 19, 2011 at 6:49 PM, Phyo Arkar  wrote:
>> I like lxml more , and check pyquery! jQuery of python at server side.
>>
>> On 9/20/11, Bruno Rocha  wrote:
>>> I dont know your needs but, you can pass any XML to web2py TAG[''] helper so
>>> then you can use Server side DOM to inspect
>>>
>>> http://web2py.com/book/default/chapter/05#Server-side-DOM-and-Parsing
>>>
>>
>


[web2py] validators

2011-09-22 Thread Chris Rowson
Quick question,

If I put my validators in the model like this:

 db.data.speedtesturl.requires=IS_NOT_IN_DB(db,
'data.speedtesturl',error_message='This speedtest URL is already in
the database. Please provide another')

They only seem to work if I use SQLFORM.

If I create a SQLFORM and then add an extra field to it like this:

speedtesturl=TR(LABEL('Speedtest
URL'),INPUT(_name='speedtesturl',_type='text',))
form[0].insert(-1,speedtesturl)

and then add the data to the database a little later like this:

db.data.insert(**dict(form.vars))

The validator doesn't validate the data from the extra field.

To validate the data in the extra field I have to call the validator
in the controller like this:

speedtesturl=TR(LABEL('Speedtest
URL'),INPUT(_name='speedtesturl',_type='text',
requires=IS_NOT_IN_DB(db, 'data.speedtesturl')))

Am I right in thinking then that validators written in the model only
work against data submitted using SQLFORM, and not against data
submitted in other ways?

Thanks,

Chris


Re: [web2py] validators

2011-09-22 Thread Chris Rowson
Ah right, cool!

Thanks Bruno,

Chris

On Thu, Sep 22, 2011 at 11:37 AM, Bruno Rocha  wrote:
> validators are originally written to work on FORMS, but web2py included an
> option to validate DAL inserts.
> db.validate_and_insert(**values)
> &
> db.validate_and_update(**values)
>
>
> On Thu, Sep 22, 2011 at 7:33 AM, Chris Rowson 
> wrote:
>>
>> Quick question,
>>
>> If I put my validators in the model like this:
>>
>>     db.data.speedtesturl.requires=IS_NOT_IN_DB(db,
>> 'data.speedtesturl',error_message='This speedtest URL is already in
>> the database. Please provide another')
>>
>> They only seem to work if I use SQLFORM.
>>
>> If I create a SQLFORM and then add an extra field to it like this:
>>
>>    speedtesturl=TR(LABEL('Speedtest
>> URL'),INPUT(_name='speedtesturl',_type='text',))
>>    form[0].insert(-1,speedtesturl)
>>
>> and then add the data to the database a little later like this:
>>
>>    db.data.insert(**dict(form.vars))
>>
>> The validator doesn't validate the data from the extra field.
>>
>> To validate the data in the extra field I have to call the validator
>> in the controller like this:
>>
>>    speedtesturl=TR(LABEL('Speedtest
>> URL'),INPUT(_name='speedtesturl',_type='text',
>> requires=IS_NOT_IN_DB(db, 'data.speedtesturl')))
>>
>> Am I right in thinking then that validators written in the model only
>> work against data submitted using SQLFORM, and not against data
>> submitted in other ways?
>>
>> Thanks,
>>
>> Chris
>
>
>
> --
>
>
>
> --
> Bruno Rocha
> [ About me: http://zerp.ly/rochacbruno ]
> [ Aprenda a programar: http://CursoDePython.com.br ]
> [ O seu aliado nos cuidados com os animais: http://AnimalSystem.com.br ]
> [ Consultoria em desenvolvimento web: http://www.blouweb.com ]
>


[web2py] Regex messes up web2py editor

2011-09-22 Thread Chris Rowson
Hi all,

I've just noticed that the web2py web-based text editor can't cope
with this regex

requires=IS_MATCH("^([Gg][Ii][Rr]
0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]
{0,1}[0-9][A-Za-z]{2})$"
It seems to cause the editor to corrupt any further text entered in.

I don't expect an answer or anything, just thought I'd point it out.

Thanks,

Chris


Re: [web2py] Re: Regex messes up web2py editor

2011-09-27 Thread Chris Rowson
I gave it a try and found that when using the 'amy' editor I can't
scroll all the way to the bottom of the text.

Never mind, thanks for the advice.

Chris

On Thu, Sep 22, 2011 at 9:55 PM,   wrote:
> I'll give it a go and see if it works. Thanks.
>
> Chris
>
>
>
> -- Sent from my HP TouchPad
> 
> On 22 Sep 2011 16:49, Anthony  wrote:
> In /admin/models/0.py, try setting:
> TEXT_EDITOR = 'amy'
> That will cause admin to use the Amy editor instead of EditArea -- see if
> that works.
> Anthony
>
> On Thursday, September 22, 2011 11:36:02 AM UTC-4, leftcase wrote:
>>
>> Hi all,
>>
>> I've just noticed that the web2py web-based text editor can't cope
>> with this regex
>>
>>             requires=IS_MATCH("^([Gg][Ii][Rr]
>>
>> 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]
>> {0,1}[0-9][A-Za-z]{2})$"
>> It seems to cause the editor to corrupt any further text entered in.
>>
>> I don't expect an answer or anything, just thought I'd point it out.
>>
>> Thanks,
>>
>> Chris
>


[web2py] DAL - Selects

2011-09-29 Thread Chris Rowson
I'm trying to learn to use the DAL.

I've been reading through chapted 6 of the web2py book and I'm sorry
if I missed the answer there, but here I go!

A user enters his/her postcode and this is checked against an API
which issues us back the 10 closest postcodes. We store the 10 closest
postcodes as a list of tuples called 'postcodes' which looks like
this:

[('0.49769486428969', 'HU12NE'), ('0.49842635239737', 'HU91DR')]

My database contains a table called data with a field named postcode

I want to then check the database and see if any of my data.postcode
fields contain a postcode which matches that returned by the postcodes
list. If they do, I want the id and the name.

Would this be done like that or am I missing the point (please forgive
typo etc, quickly typed this up in a browser)?

results=[]
for postcode in postcodes:
rows=db(db.data.postcode==postcode[1]).select()
for row in rows:
data=[row.id,row.name]
results.append(data)

Thank you!

Chris


Re: [web2py] Re: DAL - Selects

2011-10-01 Thread Chris Rowson
Thanks Peter, I'll give that a try.

Chris
On Sep 30, 2011 8:01 PM, "Peter Etchells" 
wrote:
> results=db(db.data.belongs([p[1] for p in postcodes).select()


[web2py] To DAL or not to DAL, that is the question!

2011-10-08 Thread Chris Rowson
Call me wierd, but I'm finding it a little hard to get my head around
putting together select statements using the DAL. I think I must just
be having a stupid couple of weeks!

I understand that using the DAL & SQLFORM etc for inserts will help
protect me against SQL Injection so I'm happy to keep on doing that,
but is there any particular reason I shouldn't just use db.executesql
to perform my selects (because I find it easier)?

I also understand that raw SQL queries are database specific but I
don't mind, as I don't intend to move databases.

Chris


Re: [web2py] Re: DAL - Selects

2011-10-08 Thread Chris Rowson
I finally used...

postcodelist=[]
closepostcodes=ukpostcodes.closest_postcodes(session.postcode,
str(session.distance))
for p in closepostcodes:
postcodelist.append(p[1])
rows = db(db.data.postcode.belongs==(p for p in
postcodelist)).select(db.data.download, db.data.postcode,
db.data.lat, db.data.lon, 
db.providers.name,

left=db.providers.on(db.data.provider==db.providers.id),
orderby=~db.data.download)

Seems to work!

Thanks for the advice about the range generator. I'm still learning
all this stuff :-D

Chris

On Sun, Oct 2, 2011 at 7:38 AM, Chris Rowson
 wrote:
> Thanks Peter, I'll give that a try.
>
> Chris
>
> On Sep 30, 2011 8:01 PM, "Peter Etchells" 
> wrote:
>> results=db(db.data.belongs([p[1] for p in postcodes).select()
>


Re: [web2py] Re: DAL - Selects

2011-10-08 Thread Chris Rowson
Sorry, left some cruff in from before.

It should have belongs==(...) it should just be belongs(...)

i.e.


postcodelist=[]
closepostcodes=ukpostcodes.closest_postcodes(session.postcode,
str(session.distance))
for p in closepostcodes:
postcodelist.append(p[1])
rows = db(db.data.postcode.belongs(p for p in
postcodelist)).select(db.data.download, db.data.postcode,
db.data.lat, db.data.lon, 
db.providers.name,

left=db.providers.on(db.data.provider==db.providers.id),
orderby=~db.data.download)
return dict(table=rows, message=postcodelist)

On Sat, Oct 8, 2011 at 3:53 PM, Chris Rowson
 wrote:
> I finally used...
>
>    postcodelist=[]
>    closepostcodes=ukpostcodes.closest_postcodes(session.postcode,
> str(session.distance))
>    for p in closepostcodes:
>        postcodelist.append(p[1])
>    rows = db(db.data.postcode.belongs==(p for p in
> postcodelist)).select(db.data.download, db.data.postcode,
>                                                db.data.lat, db.data.lon, 
> db.providers.name,
>
> left=db.providers.on(db.data.provider==db.providers.id),
>                                                orderby=~db.data.download)
>
> Seems to work!
>
> Thanks for the advice about the range generator. I'm still learning
> all this stuff :-D
>
> Chris
>
> On Sun, Oct 2, 2011 at 7:38 AM, Chris Rowson
>  wrote:
>> Thanks Peter, I'll give that a try.
>>
>> Chris
>>
>> On Sep 30, 2011 8:01 PM, "Peter Etchells" 
>> wrote:
>>> results=db(db.data.belongs([p[1] for p in postcodes).select()
>>
>


Re: [web2py] Re: To DAL or not to DAL, that is the question!

2011-10-08 Thread Chris Rowson
Thanks Massimo,

I'm very new at this and found the DAL a bit intimidating. I'm
beginning to get the hang of it now though so I'm sticking with it. I
think I was trying to overthink it before when in actual fact, the
more I try and get my head around it, the more sense it makes.

Chris

On Sat, Oct 8, 2011 at 4:19 PM, Massimo Di Pierro
 wrote:
> You don't mind to write engine specific queries but who is going to
> use your app will mind because the app is not going to be portable.
> Almost any query an be build using the dal.
>
> Massimo
>
> On Oct 8, 6:20 am, Chris Rowson  wrote:
>> Call me wierd, but I'm finding it a little hard to get my head around
>> putting together select statements using the DAL. I think I must just
>> be having a stupid couple of weeks!
>>
>> I understand that using the DAL & SQLFORM etc for inserts will help
>> protect me against SQL Injection so I'm happy to keep on doing that,
>> but is there any particular reason I shouldn't just use db.executesql
>> to perform my selects (because I find it easier)?
>>
>> I also understand that raw SQL queries are database specific but I
>> don't mind, as I don't intend to move databases.
>>
>> Chris


[web2py] Check to establish whether or not a record exists

2011-10-10 Thread Chris Rowson
Hi list,

I have a database table which looks like this:

postcode_cache

postcode (UNIQUE)
lat
lon
nearest

I want to test first whether or not a record exists for 'postcode' and
if a record does exist, I want to check whether the 'nearest' field
contains any data.

I've tried this:

if db(db.postcode_cache.postcode==postcode).select().first()==None:
create_a_new_postcode_record()

elif 
db(db.postcode_cache.postcode==postcode).select(db.postcode_cache.nearest)==None:
populate_the_nearest_field()

else:
nothing_to_do()


And while the check to establish whether or not a record exists seems
to work, the check to see whether or not the 'nearest' field within
the record is populated doesn't seem to work.

Can anyone tell me what I'm doing wrong please?

Thank you,

Chris


Re: [web2py] Re: Check to establish whether or not a record exists

2011-10-10 Thread Chris Rowson
Thank you Massimo :-)

Chris

On Mon, Oct 10, 2011 at 2:55 PM, Massimo Di Pierro
 wrote:
> row = db.postcode_cache(postcode=postcode)
> if not row:
> db.postcode_cache.insert(postcode=postcode,nearset=nearest)
> elif not row.nearest: row.update_record(nearset=nearest)
> else: pass # do nothing
>
> On Oct 10, 8:22 am, Chris Rowson  wrote:
>> Hi list,
>>
>> I have a database table which looks like this:
>>
>> postcode_cache
>> 
>> postcode (UNIQUE)
>> lat
>> lon
>> nearest
>>
>> I want to test first whether or not a record exists for 'postcode' and
>> if a record does exist, I want to check whether the 'nearest' field
>> contains any data.
>>
>> I've tried this:
>>
>> if db(db.postcode_cache.postcode==postcode).select().first()==None:
>>     create_a_new_postcode_record()
>>
>> elif 
>> db(db.postcode_cache.postcode==postcode).select(db.postcode_cache.nearest)= 
>> =None:
>>     populate_the_nearest_field()
>>
>> else:
>>     nothing_to_do()
>>
>> And while the check to establish whether or not a record exists seems
>> to work, the check to see whether or not the 'nearest' field within
>> the record is populated doesn't seem to work.
>>
>> Can anyone tell me what I'm doing wrong please?
>>
>> Thank you,
>>
>> Chris


Re: [web2py] Re: Server side form validation

2011-08-29 Thread Chris Rowson
Thanks for the rapid reply Massimo, It is much appreciated.

Chris
On Aug 30, 2011 12:23 AM, "Massimo Di Pierro" 
wrote:
> Validation is always performed server side.
>
> if you use FORM(INPUT()) that each input gets its own
> requires=[..]
>
> if you use SQLFORM(table) than the requires are from the
> table.field.requires.
>
> Anyway, do not use FORM(...INPUT()...) but use
> SQLFORM.factory(...Field(...)...) It is more powerful.
>
> On Aug 29, 4:45 pm, leftcase  wrote:
>> Hi group, first time post!
>>
>> A question about server side form validation.
>>
>> I have been following the tutorials on the web2py website and I'm
>> building a simple form like this in the controller:
>>
>>
form=FORM(TABLE(TR("Username:",INPUT(_type="text",_name="username",requires
=[IS_NOT_EMPTY(),
>> IS_NOT_IN_DB(db, 'users.username')])),
>>
>> TR("Email:",INPUT(_type="text",_name="email",requires=IS_EMAIL())),
>>  TR("",INPUT(_type="submit",_value="New User"
>>
>> When I do this, is web2py doing the form validation server side, or is
>> it using client side javascript methods to validate the users' input?
>> I wouldn't want the end user to turn off javascript in the browser to
>> bypass validation.
>>
>> I notice in the model I can also define my requirements like this:
>>
>> db.users.username.requires=[IS_NOT_EMPTY(), IS_NOT_IN_DB(db,
>> 'users.username')]
>>
>> What's the difference between the two ways of defining form
>> validation?
>>
>> Thanks in advance! :-)
>>
>> Chris


[web2py] Storing logged on user in database

2011-08-30 Thread Chris Rowson
Hi all,

This is my first foray into web app design and so I wondered if it
would be possible to get a bit of a sanity check on what I'm doing to
ensure I'm understanding web2py correctly.

My database has a table which should store data collected by SQLFORM
along with the ID of the logged on user who entered the data.

The relevant bits of my model look like this:


db.define_table('data',
   Field('dataowner', db.auth_user, default=auth.user.id,
writable=False, readable=False), #this points at the auth user
   Field('provider', db.providers), #points to another table
   Field('speed', 'integer'),
   Field('timestamp', default=request.now, writable=False,
readable=False))
db.data.dataowner.requires=IS_IN_DB(db,
'auth_user.id','auth_user.email') #and here shows which field to
return for a record
db.data.provider.requires=IS_IN_DB(db, 'providers.id','providers.name')
db.data.speed.requires=IS_NOT_EMPTY()
-

And the controller like this:

-
@auth.requires_login()
def adddata():
form=SQLFORM(db.data, fields=['provider', 'speed'])
if form.accepts(request.vars, session):
   #response.flash puts the flash in this page, session.flash in
the next page of the session
   session.flash = 'form accepted'
   redirect(URL(r=request, f='index'))
elif form.errors:
   response.flash = 'form has errors'
return dict(form=form)

--
My intention is to collect the provider and speed data with SQLFORM
and for the logged on user id and the timestamp to be automatically
populated. As you can see, I have used a decorator on the adddata
function to require a logged on user.

Does this look right to you?

Thanks in advance!

Chris


Re: [web2py] Re: Storing logged on user in database

2011-08-30 Thread Chris Rowson
> Looks OK at a high level. Is it working for you?

I thought it was until I logged in and out a couple of times and then
started getting an error:

"AttributeError:'NoneType' object has no attribute 'id"

Noticed a discussion here:
http://comments.gmane.org/gmane.comp.python.web2py/44801

Seems to indicate that the problem is caused because the session no
longer exists and therefore auth_user.id is none.

:-S

Chris


Re: [web2py] Re: Storing logged on user in database

2011-08-30 Thread Chris Rowson
> You could perhaps try default=auth.user_id instead. I'm not totally sure if
> that behaves differently.
> I don't usually use is_in_db() so can't say for sure how that might be
> affecting it.
> Can you provide more of the error details?

I think I *might* have fixed it about the same time as you answered!

I changed the model:

Field('dataowner', db.auth_user, default=auth.user.id if auth.user
else None, writable=False, readable=False),

In my minuscule understanding of this, I think it then allows the
model to accept 'None' as valid (although in reality 'None' should
never be recorded in the database because the decorator on the data
entry function requires the user to be logged in).

Seems to work for me as far as I've tested. What do you think?

Chris


Re: [web2py] Re: Storing logged on user in database

2011-08-31 Thread Chris Rowson
> Good to hear.
> It's possible using auth.user_id might also fix it like that.
> This is what it says in the book:
> auth.user contains a copy of the db.auth_user records for the current logged
> in user or None otherwise. There is also also a auth.user_id which is the
> same as auth.user.id (i.e. the id of the current logger in user) or None.
>

I've replaced my early change with auth.user_id and that works too.

Thank you :-)

Chris


[web2py] SQLFORM validator question

2011-08-31 Thread Chris Rowson
Hi folks,

I'm having a bit of mental blank.

I'm trying to create a validator in the model for a postcode entry in
SQLFORM to strip all spaces and non-alphanumeric characters like this:

db.data.postcode.requires=[IS_NOT_EMPTY(), CLEANUP([48-57,65-90,97-122])]

I'm getting the following error:

(unhashable type: 'list')

What am I doing wrong? :-S

Thanks

Chris


Re: [web2py] Re: SQLFORM validator question

2011-08-31 Thread Chris Rowson
Ah cool.

Thanks,

Chris

On Wed, Aug 31, 2011 at 10:30 PM, Anthony  wrote:
> CLEANUP does not actually take a list of ascii codes as an argument.
> Instead, it takes a regular expression, which defaults
> to '[^\x09\x0a\x0d\x20-\x7e]'.
> Anthony
>
> On Wednesday, August 31, 2011 5:18:43 PM UTC-4, leftcase wrote:
>>
>> Hi folks,
>>
>> I'm having a bit of mental blank.
>>
>> I'm trying to create a validator in the model for a postcode entry in
>> SQLFORM to strip all spaces and non-alphanumeric characters like this:
>>
>> db.data.postcode.requires=[IS_NOT_EMPTY(), CLEANUP([48-57,65-90,97-122])]
>>
>> I'm getting the following error:
>>
>> (unhashable type: 'list')
>>
>> What am I doing wrong? :-S
>>
>> Thanks
>>
>> Chris
>