Python CGI - including VARIABLE value in Form input CHECKBOX

I have a form which is to be used for recording activity/course selections by students. An image and description of this this form is shown below. This form (OrderFormTWO.cgi  is connected to an action page Action_OrderFormTWO.cgi.  The code for OrderformTWO.cgi is given below - along with an example of the output generated by the action page.

PROBLEM
The form includes  checkboxes for activity/course selection. The image below shows an example of this - three different courses have been selected.  Upon selection, the information is submitted to the action page via the SUBMIT button.  

I need the VALUE of each of the checkboxes to be that of the variable '#'  (Which is the unique activity/course identification number - top left column of the form  ).  This value should automatically be generated for each of the activities chosen by the the students. This is the relevant part of the code

print("""<td>
                        <input type='checkbox' name='selection' id='each' value='{0}.format(each[0])'>T1</input>
                         <input type="checkbox" name="selectionTWO" value="2">T2</input>
                         <input type="checkbox" name="selectionTHREE" value="3">T3</input>""")

Open in new window


First line shows my attempt to include the variable value. I have directly inserted VALUEs into lines 2 and 3. The action page gives the correct result for  lines 2 and 3 (T2 and T3) - but not for line 1 where the attempt to evaluate the variable value fails.  See image below

output of action page
Assuming this is a syntax problem, can someone take a look and pinpoint the problem.  I am also including below the complete code for the form page, which includes the above code - see line 60 for the function activityorderform(activities)

#!C:\Python34\python.exe
import mysql.connector as conn

import cgi,cgitb
def htmlTop():
      print("""Content-type:text/html\n\n
             <!DOCTYPE html>
             <html lang="fr">
                 <head>
                  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
                  <title> My Server-side template</title>
             <style type="text/css">
                      #floatingbutton {
                          top: 200px;
                          width: 100px;
                          right: 800px;
                          display: block;
                          z-index: 9999;
                          position: fixed;
                      }
                  </style>
     
             </head>
             <body>""")





def htmlTail():
      print(""" its done</body>
             </html>""")
      
def connectDB():
      db=conn.connect(host='localhost' ,user='root' ,passwd='' ,db='office')
      cursor = db.cursor()
      return db, cursor   

#def numberofrecords(db,cursor):
      #sql = ("select * from activities")         
      #cursor.execute(sql)
      #result = cursor.fetchone()
      #number_of_rows=result[0] + 1
      ##print(number_of_rows, "number of rows")
      #return number_of_rows
      
def numberofrecords(db,cursor):
      sql = ("select * from activities")         
      cursor.execute(sql)
      number_of_rows=len(activities)
      return number_of_rows

  
def selectactivities(db,cursor):
      sql = ("select * from activities")         
      cursor.execute(sql)
      activities = cursor.fetchall()
      return activities

def activityorderform(activities):
      print("""<form method="post" action="action_OrderFormTWO.cgi">""")
      print("<table border='1'>")
      print("<tr bgcolor=#FCFFDA>")
      print("<th>#</th>")
      print("<th>Activity</th>")
      print("<th>Jour</th>")
      print("<th>Horaire</th>")
      print("<th>Professeur</th>")
      print("<th>Trimesters</th>")
      
      print("</tr>")
      color = 1
      for each in activities:
            if color is 1:
                  print("<tr bgcolor=#BED3BE>")
            else:
                  print("<tr bgcolor=#D0F5CF>")
            print("<td>{0}</td>".format(each[0]))
            print("<td>{0}</td>".format(each[3]))
            print("<td>{0}</td>".format(each[1]))
      
             
            print("<td>{0}</td>".format(each[2]))
            print("<td>{0}</td>".format(each[4]))
            
            print("""<td>
                        <input type='checkbox' name='selection' id='each' value='{0}.format(each[0])'>T1</input>
                         <input type="checkbox" name="selectionTWO" value="2">T2</input>
                         <input type="checkbox" name="selectionTHREE" value="3">T3</input>""")
            print("</td>")       
            print("")
            print("</tr>")
            if color is 1:
                  color = 0
            else:
                  color = 1

      print("</table>")
      #print("""<input type="submit" name="formData" ID="floatingbutton value="Submit" />""")
      
      print("""<input type="submit" name="mysubmitbutton" ID="floatingbutton" value="SUBMIT" />""")
      print("</form>")      
     
#main program
if __name__== "__main__":
      try:
            htmlTop()
            db,cursor=connectDB()
            activities=selectactivities(db,cursor)
            cursor.close()
            activityorderform(activities)
            db,cursor=connectDB()
            number_of_rows=numberofrecords(db,cursor)
            print(number_of_rows, "number of rows")
            #cursor.close()
            print("qsjdflskj")
            htmlTail()

      except:
            cgi.print_exception()

Open in new window









REGISTRATION FORM

Selection Form with example 3 selections made
Column 1 '#' gives the unique activity number for each of the offerings
Columns 2,3,4,5 give activity information;
Column 6 'TRIMESTERS' provides a form with a checkbox input for each of the available activities. Example shows selections made for activities # 's  36,1,2. Each activity can be subscribed to by Trimester - there are 3 trimesters available per year T1, T2, T3 .  In the example the student has subscribed to 3 trimesters for each of the activities chosen.
Once Selected the submit button is used to submit the selection to the action page.
Error in image - sorry - should show selections T1, T2 and T3 for activity/course 2 . Activity/course 3 has been shown selected by mistake.
jameskaneAsked:
Who is Participating?
 
Walter RitzelSenior Software EngineerCommented:
my suggestion for this code:
 
print("""<td>
                        <input type='checkbox' name='selection{0}' id='selection{0}' value='1'>T1</input>
                         <input type="checkbox" name='selection{0}' id='selection{0}' value="2">T2</input>
                         <input type="checkbox" name='selection{0}' id='selection{0}' value="3">T3</input>""".format(each[0]))

Open in new window

That will result in the following:
                        <input type='checkbox' name='selection36' id='selection36' value='1'>T1</input>
                         <input type="checkbox" name='selection36' id='selection36' value="2">T2</input>
                         <input type="checkbox" name='selection36' id='selection36' value="3">T3</input>

Open in new window

Meaning that in your action data you will have form field called selection36 that may have up to 3 values in it:
>> request.form['selection36']
['1','2','3']  

Open in new window

>> request.form['selection36']
['1','2']  

Open in new window

>> request.form['selection36']
['2','3]  

Open in new window

0
 
jameskaneAuthor Commented:
Whooh !  That works !


Revised code
I have modified your solution a little as above. I have placed the variable as in VALUE.
Below is an  example with this code  - The form with an example selection and the results from the action page

example activity selectionaction page output

The new output now has the IDs included for each of the selected courses. The output
['33', '34'] ['33', '34', '35', '37'] ['33', '34']
can be read as follows
activity 33 has been selected for Trim1, Trim2 and Trim3
activity 34 has been selected for Trim1, Trim2 and Trim3
activity35 has been selected for Trim2 only
activity37 has been selected for Trim2 only
The above captures the complete order.

I will work on the above list to make it into a more usable format
like
[33,1,1,1] [34,1,1,1] [35,0,1,0] [37,0,1,0]
where 1 represents selection and 0 represents not selected. This will then be used for printing out receipt.

Question :

You will see in the example output an empty sublist []. I don't know what is in there  and how to access it if indeed it exists ???
0
 
jameskaneAuthor Commented:
Thank you very much for the spot on  solution !!

james
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.