Flask/Python - handling dropdown to open different HTML pages - python

I'm learning flask and Python along with HTML and CSS. I've got a Flask template to render a dropdown.
What I need to do is this: When you select a value from the dropdown it opens a new HTML page corresponding to the value chosen(different page for different options chosen).
I tried searching the web but couldn't get much resources. When I submit the dropdown option by submit button the page gives a error message saying:
Method Not Allowed
The method is not allowed for the requested URL.
Please guide me to the best possible solution.
Below is my code.
pro.html
<form name="startpage" method="POST" action="">
<div class="form-group">
<div class="input-group">
<select name = "method_cipher" id = "method_cipher">
<option value="Encrypt">Encrypt</option>
<option value="Decrypt">Decrypt</option>
</select>
<select name = "cipher_type" id = "cipher_type">
<option value="Caesar">Caesar</option>
<option value="Transposition">Transposition</option>
<option value="Reverse">Reverse</option>
</select>
</div>
<button type="submit" name="submit" value="success" class="btn btn-default">Submit</button>
</div>
</form>
test.py
import flask
APP = flask.Flask(__name__)
#APP.route('/')
def index():
return flask.render_template('pro.html')
#APP.route("/test" , methods=['GET', 'POST'])
def test():
if flask.request.method == 'POST':
select = flask.request.form.get('method_cipher')
if(select == 'Encrypt'):
return flask.render_template('lastpage.html')
if __name__ == '__main__':
APP.debug=True
APP.run()
EDIT - I want to open different web pages(HTML page) for the different dropdown option as chosen by the user like when user chose "Encrypt" and submit I want to open "lastpage.html" if he chose "Decrypt" then any other page and so on for different options. But it is not happening so.

Your form in pro.html sends the data to the url specified by the action attribute. If you leave that out or set it to an empty string like you did the requests goes to the same page which is /.
But you already set up the form handling in a different view function. You probably want to post to that one.
So change your form to post to the correct url
<form ... action="/test" ...>
That will work but it is not a good idea to hardcode the target url in the template. I assume you are using jinja so you can let it insert the url for you
<form ... action="{{ url_for("test") }}" ...>
Take a look at the url_for function if you haven't already.

Simply do this
<select onchange ="if (this.value)window.location.href=this.value">
<option value="/target1">test1<option>
<option value="/target2">test2<option>
</select>

Related

Pass python string value to html form select tag

I am trying to pass python string to existing HTML select tag form. On click of a button the python string value should be passed to existing select tag in html form. For example if I have button "Update" then on-click of this button a string value should be passed.
For example, On-click of "Update", the string item "colours" should be passed to existing select tag "x".
What I have done so far:
example.html
<label for="x">Select values of x:</label>
<select name="x" id="x">
<option value="">--Please select a value--</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<center>
<input type="submit" value="Update" name="action" class="btn btn-outline-primary">
</center>
example.py
from flask import Flask, render_template, request
app = Flask(__name__)
app.debug = True
#app.route('/', methods=['GET', 'POST'])
def dropdown():
x = request.form.get("x")
colours = ["Example"]
if request.method == 'POST':
action: str = request.form['action']
if 'Update' in action:
func(x)
return render_template('example.html', x=colours)
if __name__ == "__main__":
app.run()
Can anyone please let me know how to accomplish this?
PS: HTML form is not complete and needs changes to pass values from python.
I found the solution for this.
In the html select tag need to pass:
<option value="{{x}}">{{x}}</option>
But when I run the python script again, previously passed values are not shown in drop down list. I am not sure how to save passed values in html select tag form.

can i do process with form django python

there is a input and select with options in form tag. i want to get input value and option that entered. and i will do somethings on backend with python that value and option than i will return a result to website. but i dont use to forms.py. how can i do? is it possible?
<form action="" method="post">
{% csrf_token %}
<input type="text" name="getinputValue">
<select name="">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>
<button type=""class=""></button>
<p>{{result}}</p>
</form>
So, from what I understanding in your question, you want to retrieve the data from the form in your views and do something with it. You will have to give your <select> a name attribute so that you can reference it in your views.
<select name="level">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>
In your views, one of the ways you can retrieve this data is by:
def options_view(request):
level = request.POST.get('level') # get name of option as specified in the <select> tag
# here you can do something with it
print(level)
return render(request, 'home.html', {'level': level})
This is one way to do it.

Django pagination resets

I am building an application that lists certain records from a database. The database is quite large and I am building a pagination to show a specific number of rows. Currently I have set a default value for the paginate_by. Here is the class that I am using.
class HomePageView(ListView):
model = Syslog
template_name = 'home.html'
context_object_name = 'all_logs';
paginate_by = 10
def get_paginate_by(self, queryset):
return self.request.GET.get("paginate_by", self.paginate_by)
I have implemented and a feature that allows clients to change the pagination levels like so:
<form action="" method="get">
<select name="paginate_by" onchange='this.form.submit()'>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</form>
When the home page is loaded with the default value the number of pages show correctly. When a user submit another paginate_by value the number of pages change accordingly. The problem is that when the pagination parameter is changed and a user click on let's say 2nd page the paginate_by resets to the default.
Regards,
Jordan
you have to first get request path and after that you have to put a page number in
{{ request.path }} # -without GET parameters
{{ request.get_full_path }} # - with GET parameters
you have to use without get parameters
<select name="report" onchange="location = this.value;" class="form-control">
<option value="{{request.path}}?page=page_logic">1</option>
</select>
here page_logic can be 1,2,3,4 ...
I have figure out a way to do what I was looking for, so I ended up with this.
This is how the form looks like.
<form action="" method="get" id="form">
<select name="paginate_by" onchange = "this.form.submit();">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
For the pagination feature I ended up using a custom template tag that alters the ?page parameter, so when a client clicks on ?page=1 for example, he is redirected to www.example.com/?paginate_by=2&page=1 and if he clicks on ?page=2, he is redirected to www.example.com/?paginate_by=2&page=2 (without the custom tag he would be redirected to www.example.com/?paginate_by=2&page=1&page=2)

Displaying multiple flask variables from different forms at once in HTML template

I have 2 separate forms on a html template called queries.html, one for inputting a company name and one for inputting keywords as seen below.
<form method="POST">
<p>Enter Company Name:</p>
<p><input type="text" name="company_name"></p>
<p><input type="submit" value="submit"></p>
</form>
<p> Name: {{ name }} </p>
<form method="POST">
<p>Enter Keywords:</p>
<p><input type="text" name="keywords"></p>
<p><input type="submit" value="submit"></p>
</form>
<p> Keywords: {{ keywords }}</p>
I want to be able to display the form input in the paragraph tags seen below each form.
Below is the relevant flask code:
#app.route('/queries/', methods=['GET', 'POST'])
def queries():
if request.method == 'POST':
if request.form['company_name']:
name = request.form['company_name']
return render_template('queries.html', name=name)
elif request.form['keywords']:
keywords = request.form['keywords']
return render_template('queries.html', keywords=keywords)
return render_template('queries.html')
My problems are, firstly, the company name when entered does display fine where the {{ name }} element is as it should but when inputting a keyword I get a 'bad request' error. Secondly, I did previously have both inputs working but when I would use one form, it would wipe the displayed data from the other, e.g. when inputting a keyword after having already input and displayed a company name, the keyword would appear at the {{ keyword }} element as it should but the company name would disappear. After some research I may need to use AJAX to keep the all elements displayed but not sure if i'm looking in the right direction. It seems this should be a relatively simple issue to solve, please help! Thanks in advance to any responses.
In Place of :
request.form['company_name']
request.form['keywords']
Use this :
request.form.get("company_name")
request.form.get("keywords")
Flask throws error if there is no value in the form input. Using form.get the flask will try to get the value and will handle if there is no value.

Pass the id of button from django template to a view

Below is my views.py file
def view_approval(request):
utype = request.POST.get('butn')
print utype
if utype == 'APP':
#certain set of funtions
if utype == 'SRC':
#certain set of funtions
else:
#certain set of funtions
And the HTML file:
<form name="feedback22" action="{% url 'view_approval' %}" method="post">
{% csrf_token %}
<input id="bdyBtn" type="button" name="butn" value="APP" data-toggle="modal" data-target="#appModal" >
<input id="bdyBtn" type="button" name="butn" value="SRC" data-toggle="modal" data-target="#srcModal" >
</form>
I have two modals in my HTML page, used for uploading two Excel sheets. So I created a Django view named view_approval and placed the code inside it. The code gets executed depending upon the input button clicked. But the issue is, the value of the input button is not reaching the views.
When I printed the value using a print inside the view, it showed a value "None"
Thanks in advance!!

Categories

Resources