Matthew Wilson
2009-03-12 17:39:40 UTC
I store fields from form submissions into a cookie, and then when a
user hits a form, I prepopulate the form with that data.
I want to write a validator that first tries to get values from the
query string, and if that is None, then the validator should check the
cookie.
Here is what I have:
class LookInCookie(FancyValidator):
"""
Retrieves something from the cookie. Depends on a state with an
attribute named 'simple_cookie'.
"""
def __init__(self, k, d=None):
"""
Return k from the cookie, or d if it isn't there.
"""
self.k, self.d = k, d
def to_python(self, value, state=None):
log.debug("Inside LookInCookie.to_python with locals: %s"
% locals())
if hasattr(state, 'simple_cookie') \
and state.simple_cookie.has_key(self.k):
return state.simple_cookie[self.k]
else:
return self.d
So far, so good! First, the Int validator runs, then when Int fails,
I get the value from the cookie s.
However, here's where things fall apart. When there is no value
passed in, nothing comes back out!
More generally, is there a better solution to what I'm trying to do?
user hits a form, I prepopulate the form with that data.
I want to write a validator that first tries to get values from the
query string, and if that is None, then the validator should check the
cookie.
Here is what I have:
class LookInCookie(FancyValidator):
"""
Retrieves something from the cookie. Depends on a state with an
attribute named 'simple_cookie'.
"""
def __init__(self, k, d=None):
"""
Return k from the cookie, or d if it isn't there.
"""
self.k, self.d = k, d
def to_python(self, value, state=None):
log.debug("Inside LookInCookie.to_python with locals: %s"
% locals())
if hasattr(state, 'simple_cookie') \
and state.simple_cookie.has_key(self.k):
return state.simple_cookie[self.k]
else:
return self.d
from turbogears.util import Bunch
s = Bunch(simple_cookie={'city':1})
v = Any(LookInCookie('city'), validators.Int())
v.to_python('99', s)
99s = Bunch(simple_cookie={'city':1})
v = Any(LookInCookie('city'), validators.Int())
v.to_python('99', s)
v.to_python('abc', s)
1So far, so good! First, the Int validator runs, then when Int fails,
I get the value from the cookie s.
However, here's where things fall apart. When there is no value
passed in, nothing comes back out!
v.to_python('', s)
v.to_python(None, s)
How do I force validators to run even when the value is missing?v.to_python(None, s)
More generally, is there a better solution to what I'm trying to do?
--
Matthew Wilson
***@tplus1.com
http://tplus1.com
Matthew Wilson
***@tplus1.com
http://tplus1.com