Skip to content

Instantly share code, notes, and snippets.

@hetsch
Created October 20, 2012 09:23
Show Gist options
  • Save hetsch/3922752 to your computer and use it in GitHub Desktop.
Save hetsch/3922752 to your computer and use it in GitHub Desktop.
WTForms populate_obj problem
from wtforms.form import Form
from wtforms.fields import TextField, TextAreaField, FieldFist, FormField
class PluginForm(Form):
tags = TextField('Some random tags',)
files = TextField('Some random files',)
class Plugin(object):
form = PluginForm
class Page(object):
@classmethod
def register_plugin(cls, plugin):
if issubclass(plugin, Plugin) and plugin not in cls._plugins:
cls._plugins.append(plugin)
class PageForm(Form):
title = TextField('Title of the Page',)
body = TextAreaField('Enter the text for this page')
...
plugins = FieldList(FormField(PluginForm))
def __init__(self, *args, **kwargs):
super(PageForm, self).__init__(*args, **kwargs)
for plugin in Page._plugins:
plugin_form_cls = plugin.form
self.plugins.append_entry(FormField(plugin_form_cls))
Page.register_plugin(Plugin)
class AttributeDict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
def create_post(request):
post = AttributeDict()
form = PageForm(request.POST, obj=post)
"""
form.data contains following values:
{
'body': u'',
'meta_description': u'',
'meta_keywords': u'',
'title': u'seas',
'published': True,
'meta_title': u'',
'publication_end_date': datetime.datetime(2012, 11, 19, 11, 43, 44),
'plugins': [
{'files': u'xxx', 'tags': u'xxx'},
{'files': u'yyy', 'tags': u'yyy'},
],
'publication_date': datetime.datetime(2012, 10, 19, 11, 43, 44),
'in_navigation': False
}
"""
if request.POST and form.validate():
form.populate_obj(post)
return redirect('/home')
return render_to_response('edit_post.html', form=form)
@ja8zyjits
Copy link

Thank you for this gist.Check this I created this inspired from your gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment