Skip to content Skip to sidebar Skip to footer

Creating A Form From An Object In Python

Ok.. I am a noob to Python but work with PHP a lot. Basically I am trying to figure out how to take an object -- for example: {key:value,key:value} or {key:[value,value,value],key

Solution 1:

You can have a template with the structure of the html. Then you can replace #key# and #value# for the real values.

template = '<input name="#key#" value="#value#">'
html = template
data = {key:value,key:value}
for key in data.keys():
    html = html.replace("#key#", key).replace("#value#", data[value]) + "\n"
    html = html + template
#there's an extra template line here that you'll have to get rid of.
html = "\n".join(html.split("\n")[0:-1])

Something similar for your second example.

Solution 2:

If you are using forms for web sites , I recommend wtf, here is the link for Integrating with Flask.http://packages.python.org/Flask-WTF/

WTF site => http://wtforms.simplecodes.com/docs/0.6/

Solution 3:

There are a large number of options for dealing with form creation and validation in Python. If you are using Django, it has form building and validation built-in. If you are building a stand-alone tool, you have WTForms, z3c.form, deform ... and that's just the short list.

A couple of things to note, if you are coming from a PHP background:

  1. Python is not a templating language - it is a general purpose language. PHP was developed first and foremost to make it easy to create dynamic web pages - so it is extremely easy to embed PHP in HTML and call it a day. Python does not make that nearly as easy to slap something together all in one file (although you can do some pretty impressive things using only multi-line strings, concatenation and .format). You'll want to check out a templating library - take a look at Jinja2, Mako, Breve, or Chameleon and pick the one that seems most intuitive to you.

  2. You don't need to use the I_am_an_array[] construct in your HTML if you are planning on returning multiple values for a single name. Any library you use (including the built-in one) supports receiving multiple values for a single name and will handle things appropriately.

Solution 4:

Bah, whatever, teh codes:

import cgi
FIELD = '<input name="%s%s" value="%s">\n'defformulate(ob):
    def_formulate():
        for k, v in ob.iteritems():
            ifisinstance(v, list):
                for i in v:
                    yield FIELD % (k, '[]', cgi.escape(i, True))
            else:
                yield FIELD % (k, '', cgi.escape(v, True))
    return''.join(_formulate())

Post a Comment for "Creating A Form From An Object In Python"