> 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 <lat> & <lng> tags
    
lat=location.getElementsByTagName('lat')[0].toxml().replace('<lat>','').replace('</lat>','')
    
lng=location.getElementsByTagName('lng')[0].toxml().replace('<lng>','').replace('</lng>','')

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

    return georesults

Reply via email to