HTML form results in .txt file - Passing table in parameter

41 views
Skip to first unread message

Timothee Amiens

unread,
May 3, 2021, 5:21:05 AM5/3/21
to cherrypy-users
Hi everyone,

I want to get the result of a HTML form (here in my example two checkboxes, but at the end, hundreds of them) written into a .txt file (only the names of those that have been checked and sent). I do not want to use a database in order to include perfectly the results file in the linux file tree, so any process can use it.

As an example is far more illustrative than an endless descriptive debate,

Here is what I would like to work (but that don't):

HTML Form :
<FORM method="post" action="generate_file">
<TABLE>
<TR>
<TD><INPUT type="checkbox" NAME="var[]" VALUE="var1"></TD>
<TD>variable 1</TD>
</TR>
<TR>
<TD><INPUT type="checkbox" NAME="var[]" VALUE="var2"></TD>
<TD>variable 2</TD>
</TR>

<TR>
<TD><input type="submit" value="Send"></TD>
</TR>
</TABLE>
<FORM>

Python code :
    @cherrypy.expose
    def generate_file(self, var):
        
        f = open("Requested_data.txt", "w")
        
        for i in range(0,VARIABLE_NUMBER): # Here VARIABLE_NUMBER = 2
            if var[i] != '0':
                var[i] += "\n"
                f.write(var[i])
                print(var[i])

        f.close()
        
        f = codecs.open("file_generated.html", 'r', 'utf-8')
        return f

Here is what works:

HTML code :
<FORM method="post" action="generate_file">
<TABLE>
<TR>
<TD><INPUT type="checkbox" NAME="var1" VALUE="var1"></TD>
<TD>variable 1</TD>
</TR>
<TR>
<TD><INPUT type="checkbox" NAME="var2" VALUE="var2"></TD>
<TD>variable 2</TD>
</TR>
<TR>
<TD><input type="submit" value="Send"></TD>
</TR>
</TABLE>
<FORM>

Python Code:
     @cherrypy.expose
     def generate_file(self, var1='0', var2='0'):
         
         var = [var1, var2]
 
         f = open("Requested_data.txt", "w")
         
         for i in range(0,VARIABLE_NUMBER): # here VARIABLE_NUMBER = 2
             if var[i] != '0':
                 var[i] += "\n"
                 f.write(var[i])
                 print(var[i])
 
         f.close()
         
         f = codecs.open("file_generated.html", 'r', 'utf-8')
         
         return f

Here for two checkboxes, this solution works.  But once I will have many of them, it will be far more convenient to pass a table or a list, or any object the post method generates.

Thank you a lot for your precious help guys !

Cherrypygly,

Tim

Gelu Ionas

unread,
Jun 3, 2021, 3:08:26 AM6/3/21
to cherrypy-users
Hi Tim,

Don't use [] after the input name. If you remove the [], the values from all the checked boxes with the same name will be returned as a list.


Gelu
Reply all
Reply to author
Forward
0 new messages