Search code examples
pythonpython-2.7python-3.xwebapp2

How to compare posted webapp2 value to string in a form using %{name}s python


I'm a python newbie using wepapp2 as a standalone with python 2.7.5 and Mssql server express 2012.

For now, I'm trying to build a simple webpage for myself without a frame work. It's a form imported into a form handler. The handler uses string formatting to persist the form values when a required field is missing, but I'm having issues retaining values for select elements.

Debugging showed me that val type is 'str' and when outputted to HTML using %(status)r', the value was u'o', but the length of val equaled 10. I assume this is the reason why val == 'o' is false, but why? How may I get the conditional statements below to result True? Thanks.

formhandler.py

class TaskFormHandler(webapp2.RequestHandler):
    def post(self):
      ...
      col = self.request.get(field)
      ...
      if error_flag:
        self.write_display(error_flag,fields[0],...)

    def write_display(self,error='',status='',...):
       form_vals = {'error':error,'status':status,...}
       self.response.write(webview.form % form_vals)

webview.py

from string import Template

    val = '%(status)s'
    if val == 'o':
        params = dict(op1=' selected',op2='',op3='')
    elif val == 'c':
        params = dict(op1='',op2=' selected',op3='')
    elif val == 'a':
        params = dict(op1='',op2='',op3=' selected')
    else:
        params = dict(op1='',op2=' selected',op3=len(val))

    template = Template("""
        <label>Temp_Status
            <select name='status'>
                <option value='o'${op1}>Opened</option>
                <option value='c'${op2}>Completed</option>
                <option value='a'${op3}>Aged</option>
            </select>
        </label><br><br>
        """)

    form = """
<form method='post' action='/tasksystem/taskform'>
...
...
""" + template.substitute(params) + """
...
...
</form>
"""

This is the output from the webpage's page source:

<label>Temp_Status
        <select name='status'>
            <option value='o'>Opened</option>
            <option value='c' selected>Completed</option>
            <option value='a'10>Aged</option>
        </select>
    </label><br><br>

Solution

  • I dont know webapp2, but 10 is the length of %(status)s. Correct would be val = str(status) as the 1st line, I think. Or simply check for status == XX