I've summarized the ideas in this thread and in
http://docs.turbogears.org/1.0/UnifiedControllers to a nice reusable
decorator. It also solves the "Please insert a value" problem by using
a hidden field.
Here is how a unified controller method looks like using this
decorator:
@expose(template='templates.add_form_template')
@unified_validate(form=my_form):
def add(self, **data, tg_errors=None):
if tg_errors is not None:
# there are errors or form was not submitted at all.
return dict(form=my_form)
do_add(data)
# return a dictionary or redirect
In order for this to work, you must add an hidden field to your form.
unified_validate() expects the name of this field to be 'submitted',
unless you specify another name as the submit_field argument.
The rest of the arguments to this decorator are just passed directly to
turbogears' validate. The idea is to actually perform the validation
only if the hidden field is given as argument, indicating that the form
was actually submitted.
Here is the decorator code:
def unified_validate(submit_field='submitted', *v_args, **v_kwargs):
@validate(*v_args, **v_kwargs)
def get_errors(self, tg_errors=None, *args, **kwargs):
return tg_errors, args, kwargs
def decorator(func):
def newfunc(self, *args, **kwargs):
if 'submitted' in kwargs:
tg_errors, args, kwargs = get_errors(self, *args,
**kwargs)
else:
tg_errors = {submit_field: 'Form not submitted.'}
return func(self, tg_errors=tg_errors, *args, **kwargs)
return newfunc
return decorator
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"TurboGears" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/turbogears?hl=en
-~----------~----~----~----~------~----~------~--~---