HTML form submit button to execute print statement - python

I'm pretty new to html coding. I am trying to implement a simple application that asks the user to input a salutation, first name, and last name. Upon submission, instead of storing the names into a database, I just want an alert or print statement to appear below the form itself that says "Welcome" + salutation + last name.
I thought I could just implement this using a simple python script and an html file that holds all the contents. Is there something more to this?
app.py
#!/usr/bin/env python3
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def main():
return render_template('form.html')
if __name__ == "__main__":
app.run()
form.html
<html lang="en">
<body>
<div class="container">
<div class="jumbotron">
<h1>Gettin' a feel for docker</h1>
<form class="form" method= "post" onSubmit= "alert('Welcome')">
<label for="salutation" class="sr-only">Salutation</label>
<input type="salutation" name="salutation" id="salutation" class="form-control" required autofocus><br>
<label for="firstName" class="sr-only">First Name</label>
<input type="name" name="firstName" id="firstName" class="form-control" required autofocus><br>
<label for="lastName" class="sr-only">Last Name</label>
<input type="name" name="lastName" id="lastName" class="form-control" required><br>
<button id="submit" class="btn btn-lg btn-primary btn-block" type="button">Submit</button>
</form>
</div>
</div>
</body>
</html>

In order to dynamically display the results of the user input upon a button click, you will have to use jquery.
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</header>
<body>
<div class='wrapper'>
<input type='text' id='salutation'>
<input type='text' id='firstname'>
<input type='text' id='lastname'>
<button class='get_greeting'>Display</button>
<div class='results'></div>
</div>
</body>
<script>
$(document).ready(function(){
$('.wrapper').on('click', '.get_greeting', function(){
$('.results').html('<p>Welcome, '+$('#salutation').val()+' '+$('#firstname').val()+' '+$('#lastname').val()+'</p>')
});
});
</script>
</html>

The code as per your requirement in form.html should be as follow :
<html lang="en">
<body>
<div class="container">
<div class="jumbotron">
<h1>Gettin' a feel for docker</h1>
<form class="form" method= "post" onSubmit= "alert('Welcome')">
<label for="salutation" class="sr-only">Salutation</label>
<input type="salutation" name="salutation" id="salutation" class="form-control" required autofocus><br>
<label for="firstName" class="sr-only">First Name</label>
<input type="name" name="firstName" id="firstName" class="form-control" required autofocus><br>
<label for="lastName" class="sr-only">Last Name</label>
<input type="name" name="lastName" id="lastName" class="form-control" required><br>
<button id="submit" class="btn btn-lg btn-primary btn-block" type="button" onclick="show_alert()">Submit</button>
</form>
</div>
</div>
<script type="text/javascript">
function show_alert(){
alert("Welcome, "+ document.getElementById('salutation').value + " " + document.getElementById('firstName').value + " " + document.getElementById('lastName').value);
}
</script>
</body>
</html>

Related

How to use filter in views.py in Django?

I'm building a hospital management system using Django. I want to create multiple users like doctor, patient and HR. But I'm not using the user authentication system provided by django. Instead I'm trying to create registration and Login forms simply using Html and bootstrap. I'm using a model.objects.filter() function to compare the input through forms and that of the database. But I'm getting desired result. This is my login function in views.py.
def login(request):
if request.method=="POST":
user = request.POST.get('user', '')
pass1 = request.POST.get('pass', '')
val=request.POST.get('val','')
if(val[0]=='Patient'):
abc = Patient.objects.filter(username=user,password=pass1)
n = len(abc)
if n>0:
print("hii")
return HttpResponse("<h1>Invalid Credentials</h1>")
else:
return render(request, 'home/p_portal.html')
else:
efg =Doctor.objects.filter(username=user, password=pass1)
if len(efg)==0:
return HttpResponse("<h1>Invalid Credentials</h1>")
else:
return render(request, 'home/d_portal.html')
return render(request, 'home/login.html')
Login Form:
<form method="post" onsubmit="return validate()" action="/home/login/">{% csrf_token %}
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="s1" value="Patient" name='val'>
<label class="form-check-label" for="s1">
Patient
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="s2" value="Doctor" name='val'>
<label class="form-check-label" for="s2">
Doctor
</label>
</div>
</div>
<div class="form-group col-md-6">
<label for="exampleInputEmail1">Username</label>
<input type="text" class="form-control" id="exampleInputEmail1" name='user'>
<!-- <small id="emailHelp" class="form-text text-muted">We'll never share your email with
anyone else.</small>-->
</div>
<div class="form-group col-md-6">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="'pass">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-
DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
crossorigin="anonymous"></script>
</body>
<script type=text/javascript>
function validate(){
var s1=document.getElementById("s1");
var s2=document.getElementById("s2");
var user=document.getElementById("user");
if(s1.checked==true && s2.checked==true){
alert("Select only one");
return false;
}
else if(s1.checked==true){
alert("hii!"+user.value);
console.log("Patient");
return true;}
else if(s2.checked==true){
alert("hii!"+user.value);
console.log("Doctor");
return true;}
else{
alert("nothing selected");
console.log("nothing");
return false;}
}
</script>
Please suggest me a way.

How to add a button in email input?

I am trying to put a button inside an email input in a Django form.
This is the code with the button next to the email input:
<div class="container" id="notifyEmailFormContainer">
<form action="{% url "landing:notify_email_add" %}" method="post" id="notifyEmailForm">
{% csrf_token %}
<div class="form-group row">
<div class="col-sm-10 input-group" id="emailInput">
<div class="input-group-addon" id="comingSoonEmailIcon"><i class="fa fa-envelope fa fa-2x" aria-hidden="true"></i></div>
<input class="form-control" type="email" name="email" placeholder="Your email...." maxlength="255" required id="id_email"/>
</div>
<div class="col-sm-2">
<button type="button" class="btn btn-block btn-primary" onclick="addNotifyEmail()" id="submitNotifyEmail">Notify Me</button>
</div>
</div>
</form>
</div>
I have a tried a couple answers in similar questions but it seems I can't get it to work.

Submit button is not working after using Bootstrap in Bottle template

I am using bottle framework and python to make a website. After using bootstrap, the submit button of my form is not working.
Here is my code in the button3.tpl file:
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Insert Artist</h1>
</div>
<hr>
<div class="container"
<form role="form" method="post" action="/result4">
<div class="form-group">
<laber>National ID</label>
<input class="form-control" type="text" name="ID" value=""><br>
</div>
<div class="form-group">
<laber>Name</label>
<input class="form-control" type="text" name="Name" value=""><br>
</div>
<div class="form-group">
<laber>Surname</label>
<input class="form-control" type="text" name="Surname" value=""><br>
<div class="form-group">
<label>Birth Year</label>
<input class="form-control" type="number" name="Birth" min="1900" max="2016"><br>
</div>
<input class="form-control" type="submit" value="Update Information">
</form>
</div>
<hr>
</body>
Why does it not redirect in the proper link ?

Saving results of radio button click in Flask

The relevant part of my flask code is:
#app.route("/process", methods = ["GET", "POST"] )
def process_form():
#checked = request.form.getlist('option')
checked=request.form('option')
with open('checked.txt','w') as file:
file.write("%s"%checked)
# do something with checked array
return checked
and my html looks like:
<div class="container" id='tog'>
<div class="half">
<form action="/process" method="POST">
<input type="radio" name="option" value="original" />
<h3>originak value<h3>
</div>
<div class="half">
<input type="radio" name="option" value="freq" />
<h3>Term Freq<h3>
</div>
</form>
</div>
The idea is that I want to find out which radio button was selected and store the information is a text file. But that does not seem to be working.
I changed the html to:
<form action="/process" method="POST">
<div class="half">
<input type="radio" name="option" value="original" />
</div>
<div class="half">
<input type="radio" name="option" value="freq" />
</div>
<input type="submit" value="Submit">
</form>
and now I get a 400 Bad Request error
You don't have a submit button inside of your form. Add one.
<input type="submit" value="Submit!" />
Also, you probably want to change request.form('option') to request.form['option']

requests module - trying to post

I'm using the requests module with python 3.3 and am trying to post data. This is the data I'm trying to post. I've already parsed the values from the html:
<form action="/checkoutnow/2" autocomplete="off" class="proceed" id="loginForm" method="post" name="login_form" novalidate="novalidate">
<input id="loginForm" name="execution" type="hidden" value="e21s1"> <input name="token" type="hidden" value="EC-2MJ027776Y1687721"> <input id="incontext" name="incontext" type="hidden" value="0"> <input id="eventID" name="_eventId_submit" type="hidden">
<div class="" id="loginFields">
<div class="inputField emailField confidential">
<label for="email">Email</label> <input autocomplete="off" data-validate-email="true" id="email" name="email" type="email" value="">
<div class="tip tipHint">
<div class="tipArrow tipArrowFront tipHintArrowFront"></div>
<div class="tipArrow tipArrowBack tipHintArrowBack"></div>
<ul class="tipText tipHintText">
<li>Did you mean <a class="emailLink" href=""></a>?
</li>
</ul>
</div>
</div>
<div class="inputField passwordField confidential">
<label for="password">Password</label> <input autocomplete="off" id="password" maxlength="22" name="password" type="password" value="">
<div class="toolTip tip guestTooltip">
<div class="tipArrow tipArrowFront tipErrorArrowFront"></div>
<div class="tipArrow tipArrowBack tipErrorArrowBack"></div>
<div class="tipText tipErrorText">
Trouble logging in? You can try again, or <a class='submit' href='/checkoutnow/2?execution=e21s1&_eventId_guest' id='guestTooltipLink'>check out as a guest</a>
</div>
</div>
</div>
</div>
<div class="buttons varA">
<input class="btn full continue" name="_eventId_submit" type="submit" value="Log in to PayPal">
<div class="forgotPassword secondary" id="forgotPasswordSection">
<a href='/us/merchantpaymentweb?cmd=_account-recovery&from=PayPal' id='forgotPassword' target='_blank'>Forgot your password?</a>
</div>
<hr class="sep">
<a class="btn btn-secondary submit" href="/checkoutnow/2?execution=e21s1&_eventId_guest&token=EC-2MJ027776Y1687721" id="checkoutAsAGuestBtn">Pay with Debit or Credit Card</a>
</div>
</form>
And here is my code to get past this. I am using a session btw.
payload6 = {'loginFields': {'password': paypalpass, 'email': useremail}, 'token': token, 'execution': execution, 'incontext': incontext, '_eventId_submit': ''}
r = session.post(urlnow, data=payload6)
I believe my problem is with the 'loginFields' as after I post, the values are still empty.
Your POST data shouldn't have any nested dicts. password and email should be top-level keys like token and execution are, and not nested under loginFields like they are now. (I assume loginFields is in your payload now because of that <div id="loginFields">, but wrappers like that shouldn't have any effect on how the POST data is structured.)
It turns out javascript was generating more variables. Thanks for the help though.

Categories