Prevent Form from Clearing with Flask Inheritance - python

I have a form, which I would like to not get cleared out on submit (post).
I am using <option selected="selected">{{ yourvalue }}</option> to keep the value in the field before generating the other option values. The problem with this is then yourvalue is duplicated in the select box. I could remove yourvalue from the list, numbers, that goes into populating the options, but then things get out of order as the selected value appears at the top. Overall, this just seems like a clunky way to keep the selected value in the form on submit. What is the correct way to do this?
__init__py
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/', methods=["GET", "POST"])
def test():
numbers = [1, 2, 3]
if request.method == "POST":
return render_template('body.html', yourvalue=request.form['number'], numbers=numbers)
return render_template('form.html', numbers=numbers)
app.run()
form.html
<html>
<body>
<form class="form-inline" method="POST" >
<select class="form-control" id="number" name="number" required>
<option value="" disabled selected></option>
<option selected="selected">{{ yourvalue }}</option>
{% for z in numbers %}
<option value="{{ z }}">{{ z }}</option>
{% endfor %}
</select>
<input type="submit" value="Submit">
</form>
{% block body %}{% endblock %}
</body>
</html>
body.html
{% extends "form.html" %}
{% block body %}
You chose {{ yourvalue }}
{% endblock %}

Sorry I misinterpreted your question initially. Could you change the HTML to something like this? Basically adding an Jinja If statement to see if the 'yourvalue' matches 'z' and if so, add "selected" to the option.
<form class="form-inline" method="POST" >
<select class="form-control" id="number" name="number" required>
<option value="" disabled selected></option>
{% for z in numbers %}
<option {% if yourvalue = z %}
selected
{% endif %}
value="{{ z }}">{{ z }}</option>
{% endfor %}
</select>
<input type="submit" value="Submit">
</form>

Related

Handling GET and POST in same Flask view, can I pass value from form then pass it on? [duplicate]

This question already has answers here:
How to pass a variable between Flask pages?
(2 answers)
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 1 year ago.
I have a form like this
<form method="GET" action="{{ url_for('model3') }}">
<div> Choose a Model:
<select class="form-select" aria-label="Default select example" name="stage">
<option value="Post Flowering" {% if thing=='Post Flowering' %} selected {% endif %}>Post Flowering</option>
<option value="Filling" {% if thing=='Filling' %} selected {% endif %}>Filling</option>
<option value="Filling Ripening" {% if thing=='Filling Ripening' %} selected {% endif %} >Filling-Ripening</option>
<option value="Ripening" {% if thing=='Ripening' %} selected {% endif %}>Ripening</option>
</select>
<input type="submit" value="Submit">
</div>
then I have route like this
#app.route('/WheatDetect', methods=['POST', 'GET'])
def model3():
stage = request.args.get('stage')
print("stage in get-->",stage)
if request.method == 'POST':
print("stage in post-->", stage)
the problem is the first print can get what I have from select option
while the 2nd print always show none...
but I need that value to process my data, but how???
Use
<form method="POST" action="{{ url_for('model3') }}">
Instead of
<form method="GET" action="{{ url_for('model3') }}">
Due to different request method you are not get the value

Django how to retrieve values from a database for an existing post so that we can edit

I am displaying a form for a posting which has already been saved to the database. I am giving the user the option to view the values as they are in the database and give him the option to edit them. However, it is not working for dropdown. I have tried writing something but it does not display the correct values.
please help :(((
Here is the code snippet:
<div class="form-group col-md-6">
<label for="industry_type">Industry Type</label>
<select class="form-control" id="industry_type" name="industry_type" selected="
{{ internship.industry_type }}">
{% for ind_type in industry_types %}
<option value="{{ ind_type }}" {% if '{{ ind_type }}' == '{{
internship.industry_type }}' %}selected="selected" {% endif %}>
{{ind_type}}</option>
{% endfor %}
</select>
</div>
views.py
def edit_internship(request, pid):
internship = Internship.objects.get(id=pid)
skills = InternshipSkill.objects.filter(internship=internship)
emp_steps = InternshipEmpStep.objects.filter(internship=internship)
.order_by('emp_step_no')
industry_types = IndustryType.objects.all()
context = {
'industry_types': industry_types,
'internship': internship,
'skills': skills,
'emp_steps': emp_steps,
}
return render(request, 'edit_internship.html', context)
Okay this is just because don't need to re-add the curly brackets in django's templates if you already have them:
<div class="form-group col-md-6">
<label for="industry_type">Industry Type</label>
<select class="form-control" id="industry_type" name="industry_type" selected="{{ internship.industry_type.pk }}">
{% for ind_type in industry_types %}
<option value="{{ ind_type.pk }}" {% if ind_type.pk == internship.industry_type.pk %}selected="selected" {% endif %}>
{{ ind_type }}
</option>
{% endfor %}
</select>
</div>
Also, don't forget the .pk argument to ind_type when declaring the value.
For future reference, I really recommend you use Django's forms when creating these, it makes your like SO much easier:
views.py
class EditInternship(UpdateView):
model = Internship
template_name = 'edit_internship.html'
form_class = EditInternshipForm
def get_context_data(**kwargs):
ctx = super().get_context_data(**kwargs)
ctx.update(
skills=InternshipSkill.objects.filter(internship=internship),
emp_steps=InternshipEmpStep.objects.filter(internship=internship).order_by('emp_step_no')
)
# You'll also have `form` already in the context
return ctx
edit_internship = EditInternship.as_view()
forms.py
class EditInternshipForm(forms.ModelForm):
class Meta:
model = Internship
fields = 'industry_type', 'other_fields_on_the_model_you_want_to_edit'
edit_internship.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.industry_type }}
{{ form.other_fields_you_want_to_edit }}
<input type="submit" name="submit_button" value="Save" class="btn btn-primary btn-sm" id="submit_button">
</form>

To retain the form values in the jinja template

I have a form that I am using for post the data
<form enctype="multipart/form-data" method="post" action="">
<div class="form-group">
<label>Application Name <span class="mandatory">*</span></label>
<input type="text" class="form-control" name="app_name" id="appname" required maxlength="40">
<button>submit</button>
</div>
</form>
In flask i am fetching the form data and trying to do post method
if request.method == "POST":
application_data = request.form.to_dict()
postedata = post(application_data )
if posteddata:
print("sucessfully posted")
else:
print("unsucessful")
return render_template("application/addapplication.html", data=application_data)
but what I want is when else part executes that means post data doesnot happens i want to retain the values in the form. but, since here page will reload the form data is disapperaring. please can anyone help me in this?
<input type="text" value="{{ request.form.get('app_name','')}}" class="form-control" name="app_name" id="appname" required maxlength="40">
For Select tag, Let's take the data from the Flask flask_option = 'batman'.
<select>
<option {% if flask_option == "superman"%} selected {% endif %} value="superman">Clark</option>
<option {% if flask_option == "batman"%} selected {% endif %} value="batman">Bruce</option>
<option {% if flask_option == "wonderwomen"%} selected {% endif %} value="wonderwomen">Diana</option>
<option {% if flask_option == "aquaman"%} selected {% endif %} value="aquaman">Arthur</option>
</select>
If you are using API for the select options,
let's take the API response like this,
{'response': [
{'value': 'superman', 'inner_text': 'Clark'},
{'value': 'batman', 'inner_text': 'Bruce'},
{'value': 'aquaman', 'inner_text': 'Arthur'},
{'value': 'wonderwomen', 'inner_text': 'Diana'}
]}
You can iterate over the API to generate the select tag,
<select>
{% for value, text in varible_name.response %}
<option {% if flask_option == value %} selected {% endif %} value = '{{value}}'> {{text}} </option>
{% endfor %}
</select>
For textarea, you can use
<textarea>{{reqest.form.get("txt")}}</textarea>
or javascript
$('textarea').text('{{reqest.form.get("txt")}}')

django if condition not working when using variable, but when using number it's working

why this code not working, i get variable "data" from views.py
when i change data.numrooms with number like '1', it's working well, but is use data.numrooms that's not working
<select class="form-control" name="numadults">
<option value=''>No. of Adult</option>
{% for i in range %}
{% if data.numadults == i %}
<option value="{{ i }}" selected>{{ i }}</option>
{% else %}
<option value="{{ i }}">{{ i }}</option>
{% endif %}
{% endfor %}
</select>
Why not put that logic in the view and pass it to template like this:
# view
adult_range = list(map(lambda x: (x, True) if x == data.numadults else (x, False), range(1,10))
# Template
<option value=''>No. of Adult</option>
{% for i, selected in adult_range %}
{% if selected %}
<option value="{{ i }}" selected>{{ i }}</option>
{% else %}
<option value="{{ i }}">{{ i }}</option>
{% endif %}
{% endfor %}
Similarly to ruddra's solution, the easiest way to achieve this is probably to do the bulk of the logic in the view:
adults = [(element, element.number == data.numadults) for element in adult_list]
This will give you a list of two-tuples of (<adult object>, <boolean>) where the boolean represents the conditional you're trying to use in the template to decide whether to use selected attribute.
In the template, you can then base your conditional solely on that boolean:
<option value=''>No. of Adult</option>
{% for i, selected in adult_range %}
{% if selected %}
<option value="{{ i }}" selected>{{ i }}</option>
{% else %}
<option value="{{ i }}">{{ i }}</option>
{% endif %}
{% endfor %}
Note though that you can also evaluate the condition inline, in the html tag, like so:
<option value="{{ i }}" {% if selected %} selected {% endif %}>
This might make for more readable code.

How to get value from dropdown list

I'm trying to get value from dropdown box into variable and then store it. I'm new to Flask and cant find anything in the documents about it.
But I dont know how to get the value from dropdown list with request.form or any other why in that matter.
My flask code in app.py
#app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
abort(401)
title = request.form['title']
link = request.form['link']
shown = request.form['shown']
#I hardcoded the id here too see basic function.
kate = Category.query.filter_by(id = 2).first()
add_into = Entries(title, link, shown, kate)
db.session.add(add_into)
db.session.commit()
And here is the html for it.
<form action="{{ url_for('add_entry') }}" method=post class="add-entry custom">
<dl>
<dt>Title:
<dd><input type=text size=120 name=title>
<dt>Link:
<dd><input type=text size=120 name=link>
<dt>Shown:
<dd><input type=text size=120 name=shown>
<label for="customDropdown">Category</label>
<select style="display:none;" id="customDropdown">
{% for c in cate %}
{% if c.id == 1 %}
<option id="{{ c.name }}" name="{{ c.name }}" SELECTED>{{ c.name }}</option>
{% else %}
<option>{{ c.name }}</option>
{% endif %}
{% endfor %}
</select>
<dd><input class="success button" type=submit value=Post it!>
</dl>
</form>
A select tag, like an input tag, needs a "name" attribute on it if you wish to have the value passed as form data.
<select name="name" style="display:none;" id="customDropdown">
Now, you should be able to access it through request.form['name'] as you have been your input elements.

Categories