Set a variable as default in HTML select option through python - jinja2

I have a python flask code that opens the html page with select options & radio buttons. In the html POST method python reads the user inputs using 'request.form[]' and connects to Netezza tabase and using SQL fetches the result. But I am unable to get the result reflected on the same html page by preserving user selections. I am rendering the same html page again so that the result table gets refreshed on the same page; but for obvious reasons dropdowns & radio buttons will be reset.
Is there a way to set a variable as default selected value in html template (the variable would be the option that user selects during the GET method) without using php?
Also any other way by which I can get my results displayed on the same page by preserving user selections would be greatly appreciated. Thank you.
Here is my Python code:
from flask import Flask
app = Flask(__name__)
wsgi_app = app.wsgi_app
#app.route('/', methods=['GET', 'POST'])
def open_html():
if request.method == 'GET':
return render_template('SelectionPage.html')
elif request.method == 'POST':
my_duration = request.form['colorRadio']
my_region = request.form['regiom_select']
my_sport = request.form['sport_select']
##Here it connects to database and fetches the result using sql
rows=c.fetchall()
print(rows[0], '', rows[-1])
##Need help here
return render_template('SelectionPage.html', rows=rows)
connection.close()
if __name__ == '__main__':
import os
HOST = os.environ.get('SERVER_HOST', 'localhost')
try:
PORT = int(os.environ.get('SERVER_PORT', '5555'))
except ValueError:
PORT = 5555
app.run(HOST, PORT)
Here is my html (SelectionPage.html)
<html>
<body>
<form method="post">
<div>
<div>
<label><input type="radio" name="colorRadio" value="Current Month">Current Month</label>
<label><input type="radio" name="colorRadio" value="Last Month">Last Month</label>
<label><input type="radio" name="colorRadio" value="Current Quarter">Current Quarter</label>
<label><input type="radio" name="colorRadio" value="YTD">YTD</label>
</div>
<br />
<tr>
<td><span>Select Region</span></td>
<td>
<select name="region_select" class="span4">
<option value="WW">WW</option>
<option value="NA">NA</option>
<option value="AP">AP</option>
<option value="ANZ">ANZ</option>
</select>
</td>
<td><span>Brand Sport</span></td>
<td>
<select name="sport_select" class="span4">
<option value="SOCCER">SOCCER</option>
<option value="HOCKEY">HOCKEY</option>
<option value="VOLLEYBALL">VOLLEYBALL</option>
<option value="CRICKET">CRICKET</option>
</select>
</td>
</tr>
<br />
<br />
<button type="submit">Submit</button>
</form>
<div>
<h4>
<th>Country</th>
<th>Count</th>
</h4>
{% for row in rows %}
<tr>
<td>{{row[1]}}</td>
<td>{{row[0]}}</td>
</tr>
{% endfor %}
</div>
</body>
</html>

Related

How to set the name value and choice field value in html form fields without using django-forms?

Suppose I want to give user 2 option in html select tag.
i want help to, full MVC implementation in Python.
i dont want to use django form.
Sample html code:
<form method="POST">
<div class="form-row">
<div class="name">Name</div>
<div class="value">
<div class="input-group">
<input class="input--style-5" type="text" name="name" required>
</div>
</div>
</div>
<div class="form-row">
<div class="name">Applying In</div>
<div class="value">
<div class="input-group">
<div class="rs-select2 js-select-simple select--no-search">
<select name="subject" required>
<option disabled="disabled" selected="selected"> Applying Department</option>
<option>Backend</option>
<option>Mobile</option>
</select>
<div class="select-dropdown"></div>
</div>
</div>
</div>
</div>
Use option = request.GET['subject'] in a view.py which will be invoked on form submission. You will get only one option because you are selecting single option in template.
suppose we have a model like this:
from django.db import models
from django import forms
class Foo(models.Model):
CHOICES= (
('choice_one', 'choice one'),
('choice_two', 'choice two'),
)
user_choices= models.CharField(max_length=10, choices=CHOICES)
class FooForm(forms.ModelForm):
class Meta:
model = Foo
fields = ['user_choices']
views:
from django.shortcuts import redirect, render
from . import models
def user_choices(request):
url = request.META.get('HTTP_REFERER') # get last url
if request.method == 'POST':
form = models.FooForm(request.POST)
if form.is_valid():
data = models.Foo()
data.user_choices= request.GET.get('user_choices')
data.save()
return redirect(url)
return render(request, 'user_choices.html', context)
then in the template:
<form action="{% url 'app_name:user_choices' %}" method="POST"> # url to above function
<select name ='user_choices'>
<option name="user_choices" value="choice_one">choice one</option>
<option name="user_choices" value="choice_two">choice two</option>
</select>
<button type="submit">submit</button>
</form>

Contact Us button/smtplib forward details

I am using pythonanywhere to make a website. I have set up a contact us page, and I am attempting to take whatever a user submits as feedback and then forward the information to myself with smtplib. I asked about this on their forums, but they for some reason just deleted my post.
Here is my HTML code:
<title>Contact us!</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/contact.css') }}">
<div class="container">
<form action="contact">
<label for="report">Reason</label>
<select id="report" name="report">
<option value="Bug">Bug</option>
<option value="Suggestion">Suggestion</option>
<option value="Other">Other</option>
</select>
<label for="Subject">Subject</label>
<textarea id="Subject" name="Subject" placeholder="Write something.." style="height:200px"></textarea>
<input type="submit" value="Submit">
</form>
</div>
And here is the python code:
#app.route("/contact", methods=["GET", "POST"])
def feedback():
if request.method == 'GET':
return render_template("contact.html")
else:
result = "Thanks for the feedback!"
report = request.form['report']
Subject = request.form['Subject']
from email.mime.text import MIMEText
import smtplib
gmail_user = 'email#gmail.com'
gmail_password = 'password'
message = MIMEText(report)
message["Subject"] = Subject
message["From"] = gmail_user
message["To"] = gmail_user
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(gmail_user, gmail_user, message.as_string())
server.close()
return render_template('settlement_return.html',result = result)
EDIT: If I manually set report and subject to some misc text string it sends fine. But trying to get the information that someone submits is not giving any results.
As discussed in the comments above -- it looks like the problem was that you were missing the method="POST" in your form tag. That meant that the form was being submitted with the GET method, so the code in the first branch of the if statement in your view was being executed, which meant that no email was being sent.

How to pass data from html to django view to use in URL?

I'm getting an error while working with django urls. I want to pass the value of Name input field after i hit the submit button.
Let's say I've this html form-
<form method='POST' action="{% url 'submittedform' slug=[firstname] %}">
{% csrf_token %}
<div>
<label for="name">Name</label>
<input type="text" name="firstname" id="name">
</div>
<div>
<label for="email">Email</label>
<input type="email" name="useremail" id="email">
</div>
<div>
<label for=phone>Phone</label>
<input type="text" name="phonenumber" id="phone" maxlength="12" pattern="[0-9]{10}">
</div>
<input type="submit" name="" id="btn" value="Submit">
</form>
Here's my view that handling it-
def submittedform(request, slug):
if request.method == 'POST':
# do something here
return render(request,'myapp/welcome.html')
return render(request,'myapp/welcome.html')
and here's my view that's handling it-
urlpatterns = [
path('index/',views.index ,name='index'),
path('welcome/<slug:slug>/',views.submittedform, name='submittedform')
]
I'm not using django forms. How can i get welcome/name working.
If you want to pass a variable to an URL you need redirect with the value:
from django.shortcuts import redirect
return redirect("/welcome/%s/" % slug)
Change the following line
<!-- Removed the bracket -->
<form method='POST' action="{% url 'submittedform' slug=firstname %}">
<!-- Children tags here -->
</form>
Now the variables are accessible in view like
def submittedform(request, slug):
if request.method == 'POST':
name = request.POST['name']
# and more variables as you need
# do something here
# do redirect here or give some message that their form has been
# submitted for their confirmation
return render(request,'myapp/welcome.html')
return render(request,'myapp/welcome.html')

flask multiple submit button

I am using flask and jinja2 to create a simple web app to serve up a simple sklearn algorithm for predictions.
In my html I need to get 4 variables: client id, textid, textid1, textid2
It currently works when I have it all connected to one submit button. But I would like to have two submit buttons to have the client id submit at the top of the page and the textid stuff at the bottom of the page. When I try to have two submit buttons it causes the page to refresh and I not able to connect the client id to the 3 textid vars.
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST">
<input name="text", id='text', placeholder="Client ID #", value="{{ client_id|round|int }}" >
<br>
<label>Enter 3 suggestions</label>
<br>
<input name="textid", placeholder="Suggested Model ID #", value="{{ request.form['textid'] }}"/>
<input name="textid1", placeholder="Suggested Model ID #", value="{{ request.form['textid1'] }}"/>
<input name="textid2", placeholder="Suggested Model ID #", value="{{ request.form['textid2'] }}"/>
<input type="submit" >
</form>
</div>
I'm simply grabbing it in flask like this:
#app.route('/suggestion', methods=['GET', 'POST'])
def with_suggestions():
try:
client_id=request.form['text']
except:
#custom function when client id is not entered to get random one
client_id = recommender.random_client_id()
try:
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
#other functional code after this
How can I break up the html to get two submit buttons? Thanks!!
Now that you have updated your code, all you need to do is add hidden inputs to identify where the click was originated from. Also Remove the leading slash from your url_for like I did below
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST" action={{url_for('suggestion')}}>
<input name="text", id='text', placeholder="Client ID" >
<input type="hidden" name="btn_identifier" value="client_id_identifier" />
<input type="submit" >
</form>
<form method="POST" action={{url_for('suggestion')}}>
<input name="textid", id='text', placeholder="Textid1">
<input name="textid1", id='text', placeholder="textid2 ">
<input name="textid2", id='text', placeholder="Textid3">
<input type="hidden" name="btn_identifier" value="text_id_identifier" />
<input type="submit" value="Submit">
</form>
main.py
from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)
#app.route('/suggestion', methods=['GET', 'POST'])
def with_suggestions():
if request.methods == 'POST':
if request.form['btn_identifier'] == 'client_id_btn':
try:
client_id=request.form['text']
except:
# I think this would go in the second elif statement
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
elif request.form['btn_identifer'] == 'text_id_btn':
# run some code to handle a click that was originated from the second button
return render_template('index.html')
if __name__ == '__main__':
app.run()
I made some changes to your code.
index.html
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST" action={{url_for('suggestion')}}>
<input name="text", id='text', placeholder="Client ID" >
<input type="submit" >
</form>
<form method="POST" action={{url_for('suggestion')}}>
<input name="textid", id='text', placeholder="Textid1">
<input name="textid1", id='text', placeholder="textid2 ">
<input name="textid2", id='text', placeholder="Textid3">
<input type="submit" value="Submit">
</form>
</div>
main.py
from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)
#app.route('/suggestion', methods=['GET', 'POST'])
def suggestion():
if request.method == 'POST':
try:
client_id=request.form['text']
except:
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
return render_template('index.html')
if __name__ == '__main__':
app.run()
Note: Values are store in the variable, print to see
I have simplified the process of fetching the info from multiple buttons. Do note that you require the python flask framework for the "request" method.
home.html
<div class="container mt-5">
<div class="row col-4">
<form method="POST" class="form-register">
<input type="submit" name="submit_button" value="Add Email">
<input type="submit" name="submit_button" value="Clear Recipients">
</form>
</div>
</div>
run.py
if request.method == 'POST':
if request.form['submit_button'] == 'Add Email':
print("add email")
elif request.form['submit_button'] == 'Clear Recipients':
print("clear recipients")
you may refer to the link provided for more example
https://www.codegrepper.com/code-examples/python/checking+if+button+pressed+flask

How to construct url suitable for django from html form action

I have django site which I can query with various combinations of parameters. I am trying to write a html form for selecting the various combinations like so :
<form action="http://mydjangosite.com/summaryReports/" target="_blank">
<input type="radio" name="reportType" value="messageSummary" checked> messageSummary<br>
<input type="radio" name="reportType" value="countSummary"> countSummary<br>
<select name="period">
<option value="today">Today</option>
<option value="yesterday">Yesterday</option>
<option value="thisWeek">This Week</option>
<option value="lastWeek">Last Week</option>
<option value="thisMonth">This Month</option>
<option value="lastMonth">Last Month</option>
</select>
<br>
<input type="radio" name="reportFormat" value="html" checked> html<br>
<input type="radio" name="reportFormat" value="pdf"> pdf<br>
<input type="radio" name="reportFormat" value="csv"> csv<br>
<input type="radio" name="reportFormat" value="email"> email<br>
<input type="radio" name="reportFormat" value="debug"> debug<br>
<input type="submit" value="Submit">
</form>
When I press button the url generated is :
mydjangosite.com/summaryReports/?reportType=messageSummary&period=today&reportFormat=html
whereas what I require is :
mydjangosite.com/summaryReports/messageSummary/today/html
How to do it?
Thanks in advance
For this to work, you'd need a view that would process the options selected, and an url that would react to the pattern, so, your view, which should be the one associated to /summaryReports/ will do something like this:
from django.shortcuts import redirect
def rewrite_the_url(request):
return redirect('your_app:actual_reports', **request.GET.dict())
now, the url definition here is important, as your view up there will pass all the parameters to it, so you'd want:
url(r'/summaryReports/(?P<reportType>[^./]+)/(?P<period>[^./]+)/(?P<reportFormat>[^./]+)/', views.actual_reports, name='actual_reports')
Then, actual_reports should be declared as:
def actual_reports(request, reportType, period, reportFormat):
#return something
Remember that an URL represents an state of your application, it's not a decorative measure, an user can simply change the parameter of your URL and expect things to change, what we're doing here is rewriting an URL to change what we get as a query string to an URL, as Django or the UWSGI server of your choice don't have any concern over the rewriting, as you would expect with systems that user Apache + mod_rewrite, which is server tech, not an application framework.
from django.conf.urls import url, include
from sellerProfile import views
urlpatterns = [
url(r'^summaryReports'+'/(?P<reportType>[\w\-]+)'+'/(?P<period>[\w\-]+)'+'/(?P<reportFormat>[\w\-]+)/$', views.summaryReportHtml, name="summaryReports")
]
you have to create urlpattern in urls.py and in view.py file you have to get values like.
#csrf_exempt
#token_required
def summaryReports(request, reportType, period, reportFormat):
if request.method == 'GET':
print(reportType, period, reportFormat)
I did something like this:
def reportGenerator(request):
if request.method == 'GET':
QryDict = request.GET
else:
QryDict = request.POST
reportType = QryDict.get('reportType', 'rawRecords')
period = QryDict.get('period', 'today')
reportFormat = QryDict.get('reportFormat','html')
newURL = '/summaryReports/' + reportType + '/' + period + '/' + reportFormat + '/'
return redirect( newURL )
`