Inserting data to SQL Server from HTML form using Python? - python

I am building an app using Flask and part of what I am currently working on is a registration form for new employees.
I am trying to get the registration forms to send to a SQL server table but I get 42000 pyodbc.ProgrammingError when I hit the submit button.
Here is the debugger page - Image
Here is the route and function in app.py
#app.route('/add-employee', methods=['GET', 'POST'])
def add_employee():
if request.method == "POST":
employee_id = request.form['employee_id']
first_name = request.form['first_name'],
surname = request.form['surname'],
job_title = request.form['job_title']
location = request.form['location'],
reports_to = request.form['reports_to'],
business_unit = request.form['business_unit'],
address_1 = request.form['address_1'],
address_2 = request.form['address_2'],
address_3 = request.form['address_3'],
eircode = request.form['eircode'],
mobile_number = request.form['mobile_number'],
alt_email_address = request.form['alt_email_address'],
pps_number = request.form['pps_number'],
part_orfulltime = request.form['part_orfulltime']
insert_query = '''INSERT INTO hr_employee_data (employee_id, first_name, surname, address_1, address_2, address_3, eircode, mobile_number, pps_number, alt_email_address, job_title, location, reports_to, business_unit, part_orfulltime) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);'''
cursor = cnxn.cursor()
cursor.execute(insert_query, (employee_id, first_name, surname, job_title, location, reports_to, business_unit, part_orfulltime, address_1 , address_2, address_3, eircode, mobile_number, alt_email_address, pps_number))
cnxn.commit()
return redirect (url_for('hr_homepage'))
return render_template("add-employee.html")
And the HTML form is here -
<form class="form-detail" action="{{ url_for('add_employee') }}" method="POST" id="myform">
<div class="form-left">
<h2>General Infomation</h2>
<div class="form-group">
<div class="form-row form-row-1">
<input type="text" name="first_name" id="first_name" class="input-text" placeholder="First Name" required>
</div>
<div class="form-row form-row-2">
<input type="text" name="surname" id="surname" class="input-text" placeholder="Surname" required>
</div>
<div class="form-row form-row-2">
<input type="text" name="job_title" id="job_title" class="input-text" placeholder="Job Title" required>
</div>
</div>
<div class="form-row">
<div class="form-row form-row-5">
<input type="text" name="pps_number" id="pps_number" class="input-text" placeholder="PPS Number" required>
</div>
<div class="form-row form-row-5">
<input type="text" name="employee_id" id="employee_id" class="input-text" placeholder="Employee ID" required>
</div>
</div>
<div class="form-row">
<i class="fas fa-warehouse"></i>
<select name="location">
<option class="option" value="location" selected disabled>Select Location</option>
<option class="option" value="Ballyhaunis">Ballyhaunis</option>
<option class="option" value="Kiltimagh">Kiltimagh</option>
<option class="option" value="Dublin">Dublin</option>
<option class="option" value="Store">Store</option>
<option class="option" value="On The Road">On The Road</option>
<option class="option" value="Home">Home</option>
</select>
<span class="select-btn">
<i class="fas fa-chevron-down"></i>
</span>
</div>
<div class="form-row">
<i class="fas fa-user-tie"></i>
<select name="reports_to">
<option value="position" selected disabled>Select Line Manager</option>
<option value="Manager A">Manager A</option>
<option value="Manager B">Manager B</option>
<option value="Manager C">Manager C</option>
<option value="Manager D">Manager D</option>
<option value="Manager E">Manager E</option>
<option value="Manager F">Manager F</option>
</select>
<span class="select-btn">
<i class="fas fa-chevron-down"></i>
</span>
</div>
<div class="form-group">
<div class="form-row form-row-5">
<select name="business_unit">
<option value="department" selected disabled>Select Department</option>
<option value="IT">IT</option>
<option value="Warehouse">Warehouse</option>
<option value="Purchasing">Purchasing</option>
<option value="Sales">Sales</option>
<option value="Maintenance">Maintenance</option>
<option value="Driver">Driver</option>
<option value="Management">Management</option>
</select>
<span class="select-btn">
<i class="fas fa-chevron-down"></i>
</span>
</div>
<div class="form-row form-row-5">
<select name="part_orfulltime">
<option value="time" selected disabled>Part/Full Time</option>
<option value="Part">Part Time</option>
<option value="Full">Full Time</option>
</select>
<span class="select-btn">
<i class="fas fa-chevron-down"></i>
</span>
</div>
</div>
</div>
<div class="form-right">
<h2>Contact Details</h2>
<div class="form-row-2">
<input type="text" name="address_1" class="input-text" id="address_1" placeholder="Street" required>
</div>
<div class="form-row-2">
<input type="text" name="address_2" class="input-text" id="address_2" placeholder="Town" required>
</div>
<div class="form-row-2">
<input type="text" name="address_3" class="input-text" id="address_3" placeholder="County" required>
</div>
<div class="form-row-2">
<input type="text" name="eircode" class="input-text" id="eircode" placeholder="Eircode" required>
</div>
<div class="form-group">
<div class="form-row form-row-2">
<input type="text" name="mobile_number" class="mobile_number" id="mobile_number" placeholder="Phone Number" required>
</div>
</div>
<div class="form-row">
<input type="text" name="alt_email_address" id="alt_email_address" class="input-text" required pattern="[^#]+#[^#]+.[a-zA-Z]{2,6}" placeholder="External Email">
</div>
<div class="form-row-last">
<input type="submit" name="register" class="register" value="Next">
</div>
</div>
</form>
The debugger says that each field is invalid data types but that shouldn't be the case as I have checked all those on MSSMS and nothing seems to be out of place?
I know I had one or two field names that needed to be fixed but I got all those too so out of ideas as to what might be wrong.
I looked for answers on other questions such as these -
Python Flask - Receive data from form with multiple textboxes
Recommendations for handling HTML form data using PHP - and may Python?
Python form drop down options populated by sql
However those questions don't seem to have what I am looking for. Can you see where I am going wrong?
Any advice (or previously posted solutions) would be mighty, thank you!
(Edit) P.S. Forgot to add in, if I change cursor to executemany, I get TypeError: ('Params must be in a list, tuple, or Row', 'HY000') as an error.

Related

I want to enable or disable fields for some users from admin panel

This is template
<div class="container mt-3">
<h5 class="card-title">Kindly enter the details. All details are required</h5>
<form class="row g-3" method="post" action="{% url 'home' %}" enctype="multipart/form-data">
{% csrf_token %}
<div class="col-md-4">
<label for="name" class="form-label">Full Name</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="col-md-4">
<label for="parentage" class="form-label">Father's Name</label>
<input type="text" class="form-control" id="parentage" name="father" required >
</div>
<div class="col-md-4">
<label for="mothername" class="form-label">Mother's Name</label>
<input type="text" class="form-control" id="mothername" name="mother" required>
</div>
<div class="col-md-4">
<label for="phonenumber" class="form-label">Phone number</label>
<input type="tel" class="form-control" id="phonenumber" name="pnumber" required>
</div>
<div class="col-md-4">
<label for="ephonenumber" class="form-label">Emergency contact number</label>
<input type="tel" class="form-control" id="ephonenumber" name="enumber" required>
</div>
<div class="col-md-4">
<label for="dob" class="form-label">Date of Birth</label>
<input type="date" class="form-control" id="dob" name="dob" required>
</div>
<div class="col-12">
<label for="inputAddress" class="form-label">Address</label>
<input type="text" class="form-control" id="inputAddress" placeholder="" name="address" required>
</div>
<div class="col-md-6">
<label for="photo" class="form-label">Upload a photo</label>
<input type="file" class="form-control" id="photo" name="photo" accept="image/*,.pdf" required>
</div>
<div class="col-md-4">
<label for="schoolname" class="form-label">School Name</label>
<input type="text" class="form-control" id="schoolname" name="sname" required >
</div>
<div class="col-md-4">
<label for="inputState" class="form-label">Role</label>
<select id="select" class="form-select" name="role" required>
<option selected>Choose...</option>
<option value="student">Student</option>
<option value="teacher">Teacher</option>
</select>
</div>
<div id="show">
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
This is models.py
class Student(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,null=True)
fullname= models.CharField(max_length=50)
father = models.CharField(max_length=30)
mother = models.CharField(max_length=30)
phno=models.IntegerField()
ephno = models.IntegerField()
dob=models.DateField()
address=models.CharField(max_length=100)
photo= models.ImageField(upload_to='photos/')
role=models.CharField(max_length=20)
rollNumber = models.IntegerField()
standard = models.CharField( max_length=10)
def __str__(self):
return self.fullname
This is admin.py
class studentAdmin(ExportActionMixin,admin.ModelAdmin):
list_display=('fullname', 'father',"mother",'phno','ephno',"dob",'address','photo','role','rollNumber','standard')
admin.site.register(Student,studentAdmin)
class teacherAdmin(ExportActionMixin,admin.ModelAdmin):
list_display=('fullname', 'father',"mother",'phno','ephno',"dob",'address','photo','role')
list_filter =['user']
admin.site.register(Teacher,teacherAdmin)
I want admin to enable or disable form fields and model fields from the admin panel.
Is there any way to do the same? For some users, I want to for example keep the mother's name and for some, I want to hide to it

Can not select drop down menu using python Selenium

Hi I am working with selenium and have successfully set the text field with id historicalDatePicker but unable to select options from drop down menu in <div class="dropdown historical__month"> and <div class="dropdown historical__year"> I am confused because there is no id and I am not good at using xpath. Here is the HTML code
<div class="section section--green">
<div class="forms">
<div class="form">
<div class="form__fields form__fields--widthAuto">
<div class="form__field">
<div class="form__field__label">SEARCH BY DATE</div>
<div class="form__field__text">
<input type="text" name="date" autocomplete="new-password" id="historicalDatePicker" data-latest="1577448902000">
</div>
</div>
<div class="form__field">
<button class="form__button" id="historicalSearchBtn">SEARCH</button>
</div>
<div class="form__field"></div>
<div class="form__field"></div>
</div>
</div>
<div class="form__ruler form__ruler--vertical"></div>
<div class="form">
<div class="form__fields form__fields--widthAuto">
<div class="form__field">
<div class="form__field__label">SEARCH BY SYMBOL</div>
<div class="historical__search autocomplete">
<input id="historicalSymbolSearch" autocomplete="new-password" type="text" placeholder="Search for symbols or company"><i class="icon-search"></i></div>
</div>
<div class="form__field">
<div class="form__field__label"> </div>
<div class="dropdown historical__month">
<select class="dropdown__select" name="sector">
<option value="">Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
</div>
</div>
<div class="form__field">
<div class="form__field__label"> </div>
<div class="dropdown historical__year">
<select class="dropdown__select" name="sector">
<option value="">Year</option>
<option value="2019">2019</option>
<option value="2018">2018</option>
<option value="2017">2017</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
</select>
</div>
</div>
<div class="form__field">
<button class="form__button" id="historicalSymbolBtn">SEARCH</button>
</div>
</div>
</div>
<div class="form__ruler form__ruler--vertical"></div>
<div class="form">
<div class="form__fields">
<div class="form__field">
<div class="form__field__label"> </div><span> To download daily market summary, visit <br> <strong>Daily Downloads</strong> page.</span></div>
</div>
</div>
</div>
</div>
my python code is
from selenium import webdriver
from selenium.webdriver.support.ui import Select
chromedriver = "chromedriver.exe"
driver = webdriver.Chrome(chromedriver)
driver.get("https://dps.psx.com.pk/historical")
textField = driver.find_element_by_id("historicalSymbolSearch")
textField.send_keys('DWAE')
select = Select(driver.find_element_by_xpath("//select[#name='sector']"))
# all_options = select.find_elements_by_tag_name("option")
Any Help?
You can use the below xpath for the dropdown:
select = Select(driver.find_element_by_xpath("//div[#class='dropdown historical__month']//select[#class='dropdown__select']"))

How to scrpay web which need to login in with python?

I want to write a spider for scrapying http://bbs.pinggu.org/. But signing in this web should select security question yourself and answer it.
part of the web codes is:
<p class="">
<img src="/static/images/yonghu.png" class="img1">
<img src="/static/images/yonghu-btn.png" class="img2">
<input type="text" id="username" name="username" placeholder="请输入用户名或者手机号"/>
<img src="/static/images/qingchu.png" class="fl-r">
</p>
Here need to input username.
<p class="">
<img src="/static/images/password.png" class="img1">
<img src="/static/images/password-btn.png" class="img2">
<input type="password" id="password" name="password" placeholder="请输入密码"/>
</p>
Here need to input password.
<p id="select_bady">
<img src="/static/images/anquan.png" class="img1">
<img src="/static/images/anquan-btn.png" class="img2">
<input type="hidden" id="questionid" name="questionid" value="0">
<!--<select id="questionid" name="questionid" style="right:200rem;">
<option value="0" >安全提问(未设置请忽略)</option>
<option value="1">母亲的名字</option>
<option value="2" >爷爷的名字</option>
<option value="3">父亲出生的城市</option>
<option value="4">你其中一位老师的名字</option>
<option value="5">你个人计算机的型号</option>
<option value="6">你最喜欢的餐馆名称</option>
<option value="7">驾驶执照最后四位数字</option>
</select>-->
<img src="/static/images/sanjiao_03.png" class="fl-sj">
</p>
<div class="select">
<div class="input_in">
<input type="text" value="安全提问(未设置请忽略)" />
</div>
<div class="city hide">
<ul>
<li v="0">安全提问(未设置请忽略)</li>
<li v="1">母亲的名字</li>
<li v="2">爷爷的名字</li>
<li v="3">父亲出生的城市</li>
<li v="4">你其中一位老师的名字</li>
<li v="5">你个人计算机的型号</li>
<li v="6">你最喜欢的餐馆名称</li>
<li v="7">驾驶执照最后四位数字</li>
</ul>
</div>
</div>
Here need to select the questionid from 0 to 7.
<p class="answer-k answer-bottom">
<img src="/static/images/mibao-tu.png" class="img1">
<img src="/static/images/mibao-tu-btn.png" class="img2">
<input type="text" name="answer" id="answer" placeholder="请输入问题答案">
</p>
Here need to input your answer of the selected questionid.
How to semulate to login in for webs like this.

Inserting into model from controller - Odoo 10

I need to create a form in my Odoo website so external users can register for a newsletter that is sent from my Odoo. So far I have created a website template and a controller. Thus far I have managed to display the form and do a Post as well as preload some additional many2many fields I need to fill the form but the data is not saved to the database when I hit submit. I have seen the website_portal and website_hr_recruitment models that have forms for people to fill out but I can't figure out where is the data saved and how it is done.
I include the following code from my own controller for reference:
My controller:
#http.route('/contact/register', type='http', auth='public', website='true')
def register(self, redirect=None, **post):
areas_interest = request.env['iica_contacts.area_interest'].sudo().search([])
topics_interest = request.env['iica_contacts.topic_interest'].sudo().search([])
products_interest = request.env['iica_contacts.products_interest'].sudo().search([])
countries = request.env['res.country'].sudo().search([])
if post:
return request.redirect('/contact/register/success')
values = {
'areas_interest' : areas_interest,
'topics_interest' : topics_interest,
'products_interest' : products_interest,
'countries' : countries,
}
return request.render("iica_contacts.register", values)
My Template:
<template id="register">
<t t-call="website.layout">
<t t-set="title">Register</t>
<form action="/contact/register" method="post">
<input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
<div class="container">
<div class="row">
<div class="col-md-6 form-group">
<label for="first_name">First name:</label>
<input type="text" name="first_name" class="form-control" t-att-value="first_name" />
</div>
<div class="col-md-6 form-group">
<label for="last_name">Last name:</label>
<input type="text" name="last_name" class="form-control" t-att-value="last_name" />
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">Location information</div>
<div class="panel-body">
<div class="row">
<div class="col-md-12 form-group">
<label class="control-label" for="country_id">Country:</label>
<select name="country_id" class="form-control">
<option value=""> -- Select country -- </option>
<t t-foreach="countries" t-as="country">
<option t-att-value="country.id">
<t t-esc="country.name" />
</option>
</t>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="company">Company:</label>
<input type="text" name="company" class="form-control" t-att-value="company" />
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label class="control-label" for="sector">Sector:</label>
<select name="sector" class="form-control">
<option value=""> -- Select sector -- </option>
<option value="1">Public</option>
<option value="2">Private</option>
<option value="3">ONG</option>
<option value="4">International Organization</option>
<option value="5">Financial</option>
<option value="6">Other</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label class="control-label" for="language">Language:</label>
<select name="sector" class="form-control">
<option value=""> -- Select language -- </option>
<option value="1">Spanish</option>
<option value="2">English</option>
</select>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">Contact information</div>
<div class="panel-body">
<div class="row">
<div class="col-md-12 form-group">
<label class="control-label" for="email">Email:</label>
<input type="email" name="email" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label class="control-label" for="phone">Phone number:</label>
<input type="tel" name="phone" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label class="control-label" for="contact_preference">Contact preference:</label>
<select name="contact_preference" class="form-control">
<option value=""> -- Select preference -- </option>
<option value="1">Telephone</option>
<option value="2">Email</option>
<option value="3">Text message (SMS)</option>
<option value="2">All of the above</option>
<option value="2">Dont contact me</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<ul class="nav nav-tabs">
<li class="active">Products of interest</li>
<li>Areas of interest</li>
<li>Topics of interest</li>
</ul>
<div class="tab-content">
<div id="products-interest" class="tab-pane fade in active">
<h3>Products of interest</h3>
<select name="products_interest" multiple="multiple" class="form-control">
<t t-foreach="products_interest" t-as="product">
<option t-att-value="product.id">
<t t-esc="product.name" />
</option>
</t>
</select>
</div>
<div id="areas-interest" class="tab-pane fade">
<h3>Areas of interest</h3>
<select name="areas_interest" multiple="multiple" class="form-control">
<t t-foreach="areas_interest" t-as="area">
<option t-att-value="area.id">
<t t-esc="area.name" />
</option>
</t>
</select>
</div>
<div id="topics-interest" class="tab-pane fade">
<h3>Topics of interest</h3>
<select name="topics_interest" multiple="multiple" class="form-control">
<t t-foreach="topics_interest" t-as="topic">
<option t-att-value="topic.id">
<t t-esc="topic.name" />
</option>
</t>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="submit" class="btn btn-default btn-primary">
Register <span class="fa fa-long-arrow-right" />
</button>
</div>
</div>
</div>
</form>
</t>
I will really appreciate any help.
After investigating and trying a lot of stuff I managed to do this the following way:
def register(self, redirect=None, **post):
areas_interest = request.env['iica_contacts.area_interest'].sudo().search([])
topics_interest = request.env['iica_contacts.topic_interest'].sudo().search([])
products_interest = request.env['iica_contacts.products_interest'].sudo().search([])
countries = request.env['res.country'].sudo().search([])
values = {
'areas_interest' : areas_interest,
'topics_interest' : topics_interest,
'products_interest' : products_interest,
'countries' : countries,
}
if post:
error_message, valid = self._validate_form(post)
if valid == 1:
self._process_registration(post)
return request.redirect('/contact/register/success')
else:
return request.redirect('/contact/register/error')
else:
contact = request.env['iica_contacts.contact']
values.update({
'contact' : contact,
})
return request.render("iica_contacts.register", values)
The function that inserts to the model:
def _process_registration(self, post):
request.env['iica_contacts.contact'].create({
'name' : post.get('name'),
'company' : post.get('company'),
'country_id': post.get('country_id'),
'sector' : post.get('sector'),
'language' : post.get('language'),
'email' : post.get('email'),
'phone' : post.get('phone'),
'area_interest_ids' : self._process_many2may(request.httprequest.form.getlist('areas_interest')),
'product_interest_ids' : self._process_many2may(request.httprequest.form.getlist('products_interest')),
'topic_interest_ids' : self._process_many2may(request.httprequest.form.getlist('topics_interest')),
})

Redirect after form submission cgi script

I wrote a simple email script in python that takes the data from a form and emails it using boto. What I need to do now is redirect the user to another page "thankyou.html" without showing any cgi output.
HTML FORM:
<form method="post" action="/cgi-bin/iemail.py">
<div class="row uniform 50%">
<div class="6u 12u$(xsmall)">
<input type="text" name="name" id="name" value="" placeholder="Name" required="required"/>
</div>
<div class="6u 12u$(xsmall)">
<input type="text" name="company" id="company" value="" placeholder="Company Name" required="required"/>
</div>
<div class="6u 12u$(xsmall)">
<input type="text" name="phone" id="phone" value="" placeholder="Phone Number" required="required"/>
</div>
<div class="6u$ 12u$(xsmall)">
<input type="email" name="email" id="email" value="" placeholder="Email" required="required"/>
</div>
<div class="12u$">
<div class="select-wrapper">
<select name="category" id="category">
<option value="">- Category -</option>
<option value="Additional Information">Additional Information</option>
<option value="Services Request">Services Request</option>
<option value="Consulting Request">Consulting Request</option>
<option value="Development Request">Development Request</option>
<option value='Support Request'>Support Request</option>
</select>
</div>
</div>
<div class="4u 12u$(small)">
<input type="radio" id="priority-low" name="priority" checked>
<label for="priority-low">Low</label>
</div>
<div class="4u 12u$(small)">
<input type="radio" id="priority-normal" name="priority">
<label for="priority-normal">Normal</label>
</div>
<div class="4u$ 12u$(small)">
<input type="radio" id="priority-high" name="priority">
<label for="priority-high">High</label>
</div>
<div class="12u$">
<textarea name="message" id="message" placeholder="Enter your message" rows="6" required="required"></textarea>
</div>
<div class="6u 12u$(small)">
<!--<input type="checkbox" id="demo-copy" name="demo-copy">
<label for="demo-copy">Email me a copy</label>
</div>-->
<div class="6u$ 12u$(small)">
<input type="checkbox" id="human" name="human" required="required">
<label for="human">Not a robot</label>
</div>
<div class="12u$">
<ul class="actions">
<li><input type="submit" value="Send Message" class="special" /></li>
<input type="hidden" name="redirect" value="index.html" />
<li><input type="reset" value="Reset" /></li>
</ul>
</div>
</div>
</form>
Python Script:
#!/usr/bin/python2.7
import cgi
import html
import boto.ses
import cgitb; cgitb.enable() #for troubleshooting
print("Content-Type: text/html")
print
def getdata():
form = cgi.FieldStorage()
name = form["name"].value
company = form["company"].value
phone = form["phone"].value
email = form["email"].value
category = form["category"].value
message = form["message"].value
return name, company, phone, email, category, message
#main Program
if __name__=="__main__":
try:
name, company, phone, email, category, message = getdata()
conn = boto.ses.connect_to_region('us-west-2')
conn.send_email(
'admin#gmail.com',
category,
'%r, %r, %r, %r %r' % (email, name, company,
phone, message),
to_addresses = 'admin#gmail.com'
)
except:
cgi.print_exception()
I only can get redirected to the output for the cgi script, I need to send customers to thankyou.html

Categories