Redirect after form submission cgi script - python

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

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

Update the password if the user has forgotten while Login-in, Python Flask

I am trying to update the password if the user has forgotten while Login-in. But continuously it is giving the same error given below.
Bad Request: The browser (or proxy) sent a request that this server could not understand.
app.py
#app.route('/NewPassword', methods=['POST', 'GET'])
def NewPassword():
if request.method == 'POST':
OldEmail = request.form['NewPswdInputEmail']
OldPhone = request.form['NewPswdInputPhoneNo']
NewPaswd = request.form['NewPaswdInputPassword']
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute("UPDATE USERS SET Paswd='" + NewPaswd + "' WHERE Email ='" + OldEmail + "' OR Phone ='" + OldPhone + "'")
cur.connection.commit()
return "Password Updated"
return render_template('NewPassword.html')
NewPassword.html
<form action="/NewPassword" method="post" oninput='NewPaswdConPassword.setCustomValidity(NewPaswdConPassword.value != NewPaswdInputPassword.value ? "Password does not match." : "")'>
<div class="form-group">
<label for="customRadio">Select Option to Change Password Between Email & Phone No.</label>
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="customRadioInline1" name="customRadioInline" value="Email" class="custom-control-input" checked>
<label class="custom-control-label" for="customRadioInline1">Email Id</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" id="customRadioInline2" name="customRadioInline" value="Phone" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline2">Phone No.</label>
</div>
</div>
<div class="form-group" id="EmailShowHide">
<label for="NewPswdInputEmail">Email Address</label>
<input type="email" class="form-control" name="loginInputEmail" id="NewPswdInputEmail" aria-describedby="emailHelp" placeholder="Email address">
<small id="loginemailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group" id="PhoneShowHide" style="display: none">
<label for="NewPswdInputPhoneNo">Phone Number</label>
<input type="tel" id="NewPswdInputPhoneNo" name="NewPswdInputPhoneNo" class="form-control" pattern="[0-9]{4}[0-9]{2}[0-9]{4}" placeholder="Phone number">
<small id="NewPswdPhoneHelpInline" class="text-muted">Enter Valid Number</small>
</div>
<div class="form-group">
<div class="tool">
<label for="NewPaswdInputPassword">New Password</label>
<div class="input-group" id="NewPaswdShowHide">
<input type="password" class="form-control" name="NewPaswdInputPassword" id="NewPaswdInputPassword" pattern="^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,20}$" placeholder="New password" required>
<div class="input-group-append">
<a class="btn btn-primary">
<i class="bi bi-eye-slash" aria-hidden="true"></i>
</a>
</div>
</div>
<span class="tooltext">Password Must be Alphanumeric with atleast an UpperCase & LowerCase Characters</span>
<small id="NewPaswdHelpInline" class="text-muted">Must be 8-20 characters long.</small>
</div>
</div>
<div class="form-group">
<label for="NewPaswdInputConPassword">Confirm New Password</label>
<input type="password" class="form-control" name="NewPaswdConPassword" id="NewPaswdInputConPassword" placeholder="Confirm new password" required>
</div>
<button type="submit" name="Login" id="NewPaswdSubmit" class="btn btn-primary">Submit</button>
</form>
I am trying to do is, if my database "USERS" has Email or Phone no. then Paswd will get updated with the new password which is input by the user
Please tell me what I am doing wrong.
I assume you are using Flask. Is your application running in debug mode?
Running the application in debug mode can help identify where the issue is.
The issue is with the email HTML form input. When you submit a form, the data is sent as key=value pairs, in this case you are using Flask so it is a python dictionary. So in the /NewPassword route, when you request request.form['NewPswdInputEmail'], you are grabbing a value in that dictionary submitted from the form with 'NewPswdInputEmail' as a key.
In the form input the key is the name attribute.
That's why you get the KeyError because the name in the email input form has name="loginInputEmail" instead of name="NewPswdInputEmail"
All you need to do is rename loginInputEmail attribute in the email input field to NewPswdInputEmail.

I am working on a website that requires users to register and login but Having problem in adding an additional field to auth_user using django

I have this form in html of my site
<form class="row contact_form" action="." method="post" novalidate="novalidate">
{% csrf_token %}
<div class="col-md-12 form-group p_star">
<input type="text" class="form-control" id="firstname" name="first_name" value=""
placeholder="First Name" required>
</div>
<div class="col-md-12 form-group p_star">
<input type="text" class="form-control" id="lastname" name="last_name" value=""
placeholder="Last Name" required>
</div>
<div class="col-md-12 form-group p_star">
<input type="text" class="form-control" id="mobile" name="mobile" value=""
placeholder="Mobile Number" required>
</div>
<div class="col-md-12 form-group p_star">
<input type="text" class="form-control" id="email" name="email" value=""
placeholder="Email" required>
</div>
<div class="col-md-12 form-group p_star">
<input type="password" class="form-control" id="password" name="password" value=""
placeholder="Password" required>
</div>
<div class="col-md-12 form-group p_star">
<input type="password" class="form-control" id="cpassword" name="cpassword" value=""
placeholder="Confirm Password" required>
</div>
<div class="col-md-12 form-group">
<button type="submit" value="submit" class="btn_3">
SignUp
</button>
</div>
</form>
Now the problem I am facing is:
1)When I try to post data it shows me an error that username is required which i dont want(create_user() missing 1 required positional argument: 'username').
2)There is no mobile number section in auth_user which i want.
I have tried reading the django docs but couldnt understand(OnetoOne thing and custom usermodel thing I couldnt understand both)
Here is my views.py
def signup(request):
if request.method == "POST":
first_name=request.POST['first_name']
last_name=request.POST['last_name']
email=request.POST['email']
mobile=request.POST['mobile']
password=request.POST['password']
cpassword=request.POST['cpassword']
username=request.POST['username']
user=User.objects.create_user(first_name=first_name,last_name=last_name,email=email,password=password,mobile=mobile)
user.save();
return redirect('/')
else:
return render(request,"signup.html")
(The indentations are correct)
Also I want that the users can login using mobile number or email but I dint find any explanation for that.
from django.contrib.auth.models import User
...
class MyUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# add other custom fields
first_name = models.CharField(...)
...
# create as
user = User.objects.create_user(username=email,...)
my_user = MyUser.objects.create(user=user, first_name=first_name, ...)
# authenticate as
user.authenticate(username=email, password=password)
This might help
Django default auth

Inserting data to SQL Server from HTML form using 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.

Problem in getting data from form in flask

I am basically creating a flask web app which takes username from user and gets his /her codeforces data I am having a problem in extracting the email-id
from the form. I am getting the username but not the email-id.They are both in one form tag in the html file.
Error in browser:
werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: 'email-id'
<form method="POST">
<div class="field">
<label class="label">Username:</label>
<div class="control">
<input class="input" type="text" placeholder="Enter Codeforces username" name="username" value="{{user.handle}}"></input>
</div>
</div>
<div class="has-text-centered">
<input class="button is-link" name="get-info" type="submit" value="Get Info">
</div>
<div class="field">
<label class="label">EMail id:</label>
<div class="control">
<input class="input" type="text" placeholder="Enter mail id" name="email-id" value="">
</div>
</div>
<div class="has-text-centered">
<input class="button is-link" name="get-mail" type="submit" value="Get Mail">
</div>
</form>
#app.route('/',methods=['GET','POST'])
def index():
if request.method == 'POST':
username = request.form['username']
email_id = request.form['email-id']
print(email_id)
print(username)

Categories