Flask - Passing only selected fields












2














I have a flask webpage that asks for the user to select few fields and returns back output based on the fields selected.



The below code works just fine with 3 fields. If the user selects all the 3 fields there are no issues. However if any of the fields are not selected, it returns an error saying column "none" does not exist.



def template():
form = TestForm()
if form.validate_on_submit():
student_id = form.student_id.data
class_id = form.class_id.data
roll_id = form.roll_id.data
print(student_id)
print(class_id)
print(roll_id)


Could anyone assist on how I could modify this such that only fields selected are passed and the unselected fields are ignored. Thanks



Edit (HTML code):



<form action=""
enctype="multipart/form-data"
method="POST">
{{form.hidden_tag()}}
<table>

<div class="checkbox">
<label>
<input type="checkbox" name="student_id" value="student_id"> student_id
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="class_id" value="class_id"> class_id
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="roll_id" value="roll_id"> roll_id
</label>
</div>
<tr class="submit">
<td></td>
<td><button type="submit">Get the Report!</button>
</td>
</tr>
</table>
</form>


Query that runs after getting user input:



def function(*field_names):
cursor = conn.cursor()
cursor.execute('select {} from enrolments'.format(', '.join(str(field) for field in field_names)))
print(field_names)
output_file = dwh_cursor.fetchall()









share|improve this question
























  • Show your HTML and your validation code. It sounds like you have your select field value defaulting to "none". You probably want to default it to an empty string or change your validation
    – Cfreak
    Nov 21 '18 at 18:30










  • @Cfreak have included the HTML code in my initial post.
    – scott martin
    Nov 21 '18 at 18:32






  • 1




    Show us how you call function, also consider renaming it. Secondly, if field_names are coming directly from the value of your HTML, then this code is vulnerable to SQL Injection attacks. You want to specify the columns to select. Generally for checkboxes the value attribute should be a true or false value to decide if it's selected or not. The columns you select should be static and, you would use a WHERE statement in your SQL to control which rows you get back.
    – Cfreak
    Nov 21 '18 at 18:54










  • @Cfreak, this function hits a temp table that would have maximum of 10 records and this will only fetch 3 samples from that list. Sure would rename the function appropriately. However I am stuck on how to get past these non selected fields that return 'None'
    – scott martin
    Nov 21 '18 at 18:57


















2














I have a flask webpage that asks for the user to select few fields and returns back output based on the fields selected.



The below code works just fine with 3 fields. If the user selects all the 3 fields there are no issues. However if any of the fields are not selected, it returns an error saying column "none" does not exist.



def template():
form = TestForm()
if form.validate_on_submit():
student_id = form.student_id.data
class_id = form.class_id.data
roll_id = form.roll_id.data
print(student_id)
print(class_id)
print(roll_id)


Could anyone assist on how I could modify this such that only fields selected are passed and the unselected fields are ignored. Thanks



Edit (HTML code):



<form action=""
enctype="multipart/form-data"
method="POST">
{{form.hidden_tag()}}
<table>

<div class="checkbox">
<label>
<input type="checkbox" name="student_id" value="student_id"> student_id
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="class_id" value="class_id"> class_id
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="roll_id" value="roll_id"> roll_id
</label>
</div>
<tr class="submit">
<td></td>
<td><button type="submit">Get the Report!</button>
</td>
</tr>
</table>
</form>


Query that runs after getting user input:



def function(*field_names):
cursor = conn.cursor()
cursor.execute('select {} from enrolments'.format(', '.join(str(field) for field in field_names)))
print(field_names)
output_file = dwh_cursor.fetchall()









share|improve this question
























  • Show your HTML and your validation code. It sounds like you have your select field value defaulting to "none". You probably want to default it to an empty string or change your validation
    – Cfreak
    Nov 21 '18 at 18:30










  • @Cfreak have included the HTML code in my initial post.
    – scott martin
    Nov 21 '18 at 18:32






  • 1




    Show us how you call function, also consider renaming it. Secondly, if field_names are coming directly from the value of your HTML, then this code is vulnerable to SQL Injection attacks. You want to specify the columns to select. Generally for checkboxes the value attribute should be a true or false value to decide if it's selected or not. The columns you select should be static and, you would use a WHERE statement in your SQL to control which rows you get back.
    – Cfreak
    Nov 21 '18 at 18:54










  • @Cfreak, this function hits a temp table that would have maximum of 10 records and this will only fetch 3 samples from that list. Sure would rename the function appropriately. However I am stuck on how to get past these non selected fields that return 'None'
    – scott martin
    Nov 21 '18 at 18:57
















2












2








2







I have a flask webpage that asks for the user to select few fields and returns back output based on the fields selected.



The below code works just fine with 3 fields. If the user selects all the 3 fields there are no issues. However if any of the fields are not selected, it returns an error saying column "none" does not exist.



def template():
form = TestForm()
if form.validate_on_submit():
student_id = form.student_id.data
class_id = form.class_id.data
roll_id = form.roll_id.data
print(student_id)
print(class_id)
print(roll_id)


Could anyone assist on how I could modify this such that only fields selected are passed and the unselected fields are ignored. Thanks



Edit (HTML code):



<form action=""
enctype="multipart/form-data"
method="POST">
{{form.hidden_tag()}}
<table>

<div class="checkbox">
<label>
<input type="checkbox" name="student_id" value="student_id"> student_id
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="class_id" value="class_id"> class_id
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="roll_id" value="roll_id"> roll_id
</label>
</div>
<tr class="submit">
<td></td>
<td><button type="submit">Get the Report!</button>
</td>
</tr>
</table>
</form>


Query that runs after getting user input:



def function(*field_names):
cursor = conn.cursor()
cursor.execute('select {} from enrolments'.format(', '.join(str(field) for field in field_names)))
print(field_names)
output_file = dwh_cursor.fetchall()









share|improve this question















I have a flask webpage that asks for the user to select few fields and returns back output based on the fields selected.



The below code works just fine with 3 fields. If the user selects all the 3 fields there are no issues. However if any of the fields are not selected, it returns an error saying column "none" does not exist.



def template():
form = TestForm()
if form.validate_on_submit():
student_id = form.student_id.data
class_id = form.class_id.data
roll_id = form.roll_id.data
print(student_id)
print(class_id)
print(roll_id)


Could anyone assist on how I could modify this such that only fields selected are passed and the unselected fields are ignored. Thanks



Edit (HTML code):



<form action=""
enctype="multipart/form-data"
method="POST">
{{form.hidden_tag()}}
<table>

<div class="checkbox">
<label>
<input type="checkbox" name="student_id" value="student_id"> student_id
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="class_id" value="class_id"> class_id
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="roll_id" value="roll_id"> roll_id
</label>
</div>
<tr class="submit">
<td></td>
<td><button type="submit">Get the Report!</button>
</td>
</tr>
</table>
</form>


Query that runs after getting user input:



def function(*field_names):
cursor = conn.cursor()
cursor.execute('select {} from enrolments'.format(', '.join(str(field) for field in field_names)))
print(field_names)
output_file = dwh_cursor.fetchall()






python-3.x flask






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 18:32







scott martin

















asked Nov 21 '18 at 18:28









scott martinscott martin

908




908












  • Show your HTML and your validation code. It sounds like you have your select field value defaulting to "none". You probably want to default it to an empty string or change your validation
    – Cfreak
    Nov 21 '18 at 18:30










  • @Cfreak have included the HTML code in my initial post.
    – scott martin
    Nov 21 '18 at 18:32






  • 1




    Show us how you call function, also consider renaming it. Secondly, if field_names are coming directly from the value of your HTML, then this code is vulnerable to SQL Injection attacks. You want to specify the columns to select. Generally for checkboxes the value attribute should be a true or false value to decide if it's selected or not. The columns you select should be static and, you would use a WHERE statement in your SQL to control which rows you get back.
    – Cfreak
    Nov 21 '18 at 18:54










  • @Cfreak, this function hits a temp table that would have maximum of 10 records and this will only fetch 3 samples from that list. Sure would rename the function appropriately. However I am stuck on how to get past these non selected fields that return 'None'
    – scott martin
    Nov 21 '18 at 18:57




















  • Show your HTML and your validation code. It sounds like you have your select field value defaulting to "none". You probably want to default it to an empty string or change your validation
    – Cfreak
    Nov 21 '18 at 18:30










  • @Cfreak have included the HTML code in my initial post.
    – scott martin
    Nov 21 '18 at 18:32






  • 1




    Show us how you call function, also consider renaming it. Secondly, if field_names are coming directly from the value of your HTML, then this code is vulnerable to SQL Injection attacks. You want to specify the columns to select. Generally for checkboxes the value attribute should be a true or false value to decide if it's selected or not. The columns you select should be static and, you would use a WHERE statement in your SQL to control which rows you get back.
    – Cfreak
    Nov 21 '18 at 18:54










  • @Cfreak, this function hits a temp table that would have maximum of 10 records and this will only fetch 3 samples from that list. Sure would rename the function appropriately. However I am stuck on how to get past these non selected fields that return 'None'
    – scott martin
    Nov 21 '18 at 18:57


















Show your HTML and your validation code. It sounds like you have your select field value defaulting to "none". You probably want to default it to an empty string or change your validation
– Cfreak
Nov 21 '18 at 18:30




Show your HTML and your validation code. It sounds like you have your select field value defaulting to "none". You probably want to default it to an empty string or change your validation
– Cfreak
Nov 21 '18 at 18:30












@Cfreak have included the HTML code in my initial post.
– scott martin
Nov 21 '18 at 18:32




@Cfreak have included the HTML code in my initial post.
– scott martin
Nov 21 '18 at 18:32




1




1




Show us how you call function, also consider renaming it. Secondly, if field_names are coming directly from the value of your HTML, then this code is vulnerable to SQL Injection attacks. You want to specify the columns to select. Generally for checkboxes the value attribute should be a true or false value to decide if it's selected or not. The columns you select should be static and, you would use a WHERE statement in your SQL to control which rows you get back.
– Cfreak
Nov 21 '18 at 18:54




Show us how you call function, also consider renaming it. Secondly, if field_names are coming directly from the value of your HTML, then this code is vulnerable to SQL Injection attacks. You want to specify the columns to select. Generally for checkboxes the value attribute should be a true or false value to decide if it's selected or not. The columns you select should be static and, you would use a WHERE statement in your SQL to control which rows you get back.
– Cfreak
Nov 21 '18 at 18:54












@Cfreak, this function hits a temp table that would have maximum of 10 records and this will only fetch 3 samples from that list. Sure would rename the function appropriately. However I am stuck on how to get past these non selected fields that return 'None'
– scott martin
Nov 21 '18 at 18:57






@Cfreak, this function hits a temp table that would have maximum of 10 records and this will only fetch 3 samples from that list. Sure would rename the function appropriately. However I am stuck on how to get past these non selected fields that return 'None'
– scott martin
Nov 21 '18 at 18:57














1 Answer
1






active

oldest

votes


















0














HTML checkboxes only submit if checked. It looks like you're using flask-wtforms and that is what is giving you the None values for checkboxes that aren't checked to work around this feature. You could just make sure you're getting actual field names like this:



for field in field_names:
if field:
cursor.execute('select {} from enrolments'.format(', '.join(str(field)))


Which would prevent None from going into the query, but this is a terrible and sloppy idea. Even with the CRSF token, you open yourself up to an attacker spoofing your form and executing arbitrary SQL.



You should consider using an ORM like flask-sqlalchemy or else, at least restrict what a valid field_name looks like:



for field in field_names:
if field in ['student_id', 'class_id', 'roll_id']:
cursor.execute('select {} from enrolments'.format(', '.join(str(field)))





share|improve this answer























  • when I try the above it returns an error cursor.execute('select {} from enrolments'.format(', '.join(str(field)))) psycopg2.ProgrammingError: column "s" does not exist in enrolments
    – scott martin
    Nov 22 '18 at 9:40












  • Can you examine the field_names object and tell me what it looks like, as well as how function() is invoked? It may be that submitting one field results in field_names being interpreted as a string, and field being each letter in the string.
    – Logan Bertram
    Nov 23 '18 at 12:59











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53418432%2fflask-passing-only-selected-fields%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














HTML checkboxes only submit if checked. It looks like you're using flask-wtforms and that is what is giving you the None values for checkboxes that aren't checked to work around this feature. You could just make sure you're getting actual field names like this:



for field in field_names:
if field:
cursor.execute('select {} from enrolments'.format(', '.join(str(field)))


Which would prevent None from going into the query, but this is a terrible and sloppy idea. Even with the CRSF token, you open yourself up to an attacker spoofing your form and executing arbitrary SQL.



You should consider using an ORM like flask-sqlalchemy or else, at least restrict what a valid field_name looks like:



for field in field_names:
if field in ['student_id', 'class_id', 'roll_id']:
cursor.execute('select {} from enrolments'.format(', '.join(str(field)))





share|improve this answer























  • when I try the above it returns an error cursor.execute('select {} from enrolments'.format(', '.join(str(field)))) psycopg2.ProgrammingError: column "s" does not exist in enrolments
    – scott martin
    Nov 22 '18 at 9:40












  • Can you examine the field_names object and tell me what it looks like, as well as how function() is invoked? It may be that submitting one field results in field_names being interpreted as a string, and field being each letter in the string.
    – Logan Bertram
    Nov 23 '18 at 12:59
















0














HTML checkboxes only submit if checked. It looks like you're using flask-wtforms and that is what is giving you the None values for checkboxes that aren't checked to work around this feature. You could just make sure you're getting actual field names like this:



for field in field_names:
if field:
cursor.execute('select {} from enrolments'.format(', '.join(str(field)))


Which would prevent None from going into the query, but this is a terrible and sloppy idea. Even with the CRSF token, you open yourself up to an attacker spoofing your form and executing arbitrary SQL.



You should consider using an ORM like flask-sqlalchemy or else, at least restrict what a valid field_name looks like:



for field in field_names:
if field in ['student_id', 'class_id', 'roll_id']:
cursor.execute('select {} from enrolments'.format(', '.join(str(field)))





share|improve this answer























  • when I try the above it returns an error cursor.execute('select {} from enrolments'.format(', '.join(str(field)))) psycopg2.ProgrammingError: column "s" does not exist in enrolments
    – scott martin
    Nov 22 '18 at 9:40












  • Can you examine the field_names object and tell me what it looks like, as well as how function() is invoked? It may be that submitting one field results in field_names being interpreted as a string, and field being each letter in the string.
    – Logan Bertram
    Nov 23 '18 at 12:59














0












0








0






HTML checkboxes only submit if checked. It looks like you're using flask-wtforms and that is what is giving you the None values for checkboxes that aren't checked to work around this feature. You could just make sure you're getting actual field names like this:



for field in field_names:
if field:
cursor.execute('select {} from enrolments'.format(', '.join(str(field)))


Which would prevent None from going into the query, but this is a terrible and sloppy idea. Even with the CRSF token, you open yourself up to an attacker spoofing your form and executing arbitrary SQL.



You should consider using an ORM like flask-sqlalchemy or else, at least restrict what a valid field_name looks like:



for field in field_names:
if field in ['student_id', 'class_id', 'roll_id']:
cursor.execute('select {} from enrolments'.format(', '.join(str(field)))





share|improve this answer














HTML checkboxes only submit if checked. It looks like you're using flask-wtforms and that is what is giving you the None values for checkboxes that aren't checked to work around this feature. You could just make sure you're getting actual field names like this:



for field in field_names:
if field:
cursor.execute('select {} from enrolments'.format(', '.join(str(field)))


Which would prevent None from going into the query, but this is a terrible and sloppy idea. Even with the CRSF token, you open yourself up to an attacker spoofing your form and executing arbitrary SQL.



You should consider using an ORM like flask-sqlalchemy or else, at least restrict what a valid field_name looks like:



for field in field_names:
if field in ['student_id', 'class_id', 'roll_id']:
cursor.execute('select {} from enrolments'.format(', '.join(str(field)))






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 23 '18 at 19:22

























answered Nov 21 '18 at 19:08









Logan BertramLogan Bertram

745416




745416












  • when I try the above it returns an error cursor.execute('select {} from enrolments'.format(', '.join(str(field)))) psycopg2.ProgrammingError: column "s" does not exist in enrolments
    – scott martin
    Nov 22 '18 at 9:40












  • Can you examine the field_names object and tell me what it looks like, as well as how function() is invoked? It may be that submitting one field results in field_names being interpreted as a string, and field being each letter in the string.
    – Logan Bertram
    Nov 23 '18 at 12:59


















  • when I try the above it returns an error cursor.execute('select {} from enrolments'.format(', '.join(str(field)))) psycopg2.ProgrammingError: column "s" does not exist in enrolments
    – scott martin
    Nov 22 '18 at 9:40












  • Can you examine the field_names object and tell me what it looks like, as well as how function() is invoked? It may be that submitting one field results in field_names being interpreted as a string, and field being each letter in the string.
    – Logan Bertram
    Nov 23 '18 at 12:59
















when I try the above it returns an error cursor.execute('select {} from enrolments'.format(', '.join(str(field)))) psycopg2.ProgrammingError: column "s" does not exist in enrolments
– scott martin
Nov 22 '18 at 9:40






when I try the above it returns an error cursor.execute('select {} from enrolments'.format(', '.join(str(field)))) psycopg2.ProgrammingError: column "s" does not exist in enrolments
– scott martin
Nov 22 '18 at 9:40














Can you examine the field_names object and tell me what it looks like, as well as how function() is invoked? It may be that submitting one field results in field_names being interpreted as a string, and field being each letter in the string.
– Logan Bertram
Nov 23 '18 at 12:59




Can you examine the field_names object and tell me what it looks like, as well as how function() is invoked? It may be that submitting one field results in field_names being interpreted as a string, and field being each letter in the string.
– Logan Bertram
Nov 23 '18 at 12:59


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53418432%2fflask-passing-only-selected-fields%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

TypeError: fit_transform() missing 1 required positional argument: 'X'