Using django.newforms with Pylons
November 26th, 2007Django recently got a nifty newforms library while Pylons still hesitates what is “the best” way to deal with forms.
What if Django’s newforms library were available to Pylons project? It is.
It actually is quite easy to get it up and running. Basically, you just tweak code snippets from the documentation for Pylons. The only caveat is that it depends on — not true, see below.'DJANGO_SETTINGS_MODULE
environment variable
I have built a simple pylonsnewforms-1.0rel1.tar.gz project which demostrates the concept. Here are bulk of the changes I made from stock paster create --template=pylons
.
1. A Mako page template
<form action=\"${h.url_for('djform')}\" method=\"post\">
<table>
${c.form.as_table()}
</table>
${h.submit(u'Submit')}
</form>
2. A controller
class DjangotestController(BaseController):
def index(self):
if request.method == 'POST':
c.form = ContactForm(request.POST)
if c.form.is_valid():
c.submitted_data = c.form.cleaned_data
else:
# init form with pre-populated data
data = {'subject': 'hello',
'cc_myself': True}
c.form = ContactForm(data)
return render('/djforms.mako')
3. config/environment.py
from django.conf import settings
settings.configure()
This does django configuration explicitly, thanks readers for the tip.
That’s it. Simple, eh?
One thing left out is form_for_model django’s function which generates form for you using model metadata. I am sure this is doable for SQLAlchemy models; this is what FormAlchemy and TurboGears’ FastData efforts were trying to achieve.
I am interested in your opinion so pls comment here or in the pylons-dicuss mailing list.