How do I set the VALUE attribut of a text input field (HTML forms).
I tried it with:
Python:
#app.route("/function_a", methods=['GET', 'POST'])
def function_a():
form = ReusableForm(request.form)
query = "test value"
if request.method == 'POST':
name=request.form['name']
return render_template('zeit.html', form=form, query_test=query)
HTML template:
{{ form.name(value="{{ query_test }}") }}
the website output is like:
<input id="name" name="name" required type="text" value="{{query_test}}">
expected website output:
<input id="name" name="name" required type="text" value="test value">
I got the solution:
in the HTML template I wrote only the variable without the brackets.
{{ form.name(value=query_test) }}
and the output is like I want it:
<input id="name" name="name" required type="text" value="test value">
Related
i have html file that contains both login and signup form
<form method = "POST" enctype="multipart/form-data" >
{{ user_form.as_p }}
{% csrf_token %}
<input type="text" id="firstname" placeholder="First Name" name = "first_name" required>
<div class="invalid-feedback">Please enter a valid first name.</div>
<input type="text" class="input-field" id="lastname" name = "last_name" placeholder="Last Name" required>
<div class="invalid-feedback">Please enter a valid last name.</div>
</form>
and a similar login form
how to write a single view for both of these forms using buttons
i have already seen How can I build multiple submit buttons django form? this but i didn't found useful
def user_login:
if request.method == 'POST' and request.POST.get('submit') == 'name1':
pass
elif request.method == 'POST' and request.POST.get('submit') == 'name2':
pass
in this how to write else code if request.method not POST for every form
I am new at this and trying to submit a basic form which has a dropdown list and 2 text fields. The lists value is the path of the flask route which needs to be submitted the data.
Depending on the item the user selects from the list, i would like to submit the form with data to that url, eg if user selects "a" then i would like to submit form to http://url/url1. How can this be done?
<form action="" class="form1" method="get">
<select class="form-control" id="function" name="cars">
<option value="/url1">a</option>
<option value="/url2">b</option>
<option value="/url3">c</option>
</select>
<input class="form-control" type="number" name="number1" value="">
<input class="form-control" type="number" name="number2" value="">
<input class="form-control" type="submit">
</form>
I have python flask code on server :
#app.route("/url1")
def url1():
num1=request.args.get('number1',default=-1,type=int)
num2=request.args.get('number2',default=-1,type=int)
evaluate the numbers and return render_template()
#app.route("/url2")
def url2():
num1=request.args.get('number1',default=-1,type=int)
num2=request.args.get('number2',default=-1,type=int)
evaluate the numbers and return render_template()
if i understand your question , you can solve it by jquery
code sample
$("#function").change(function() {
var action = $(this).val();
$("#form1").attr("action",action);
});
or
you can set a default action for the form and then in route do according to the selected value
I used redirection in app.py to resolve this
<form action="/submit" class="form1" method="get">
and then
#app.route('/submit', methods=['GET'] )
def submit():
num=request.args.get('number1',default=-1, type=int)
return redirect(url_for('url1', m=num))
#app.route("/url1")
def url1():
evaluate the numbers and return render_template()
When I wanted use my registration form in my site, I get ERROR 403: "CSRF verification failed. Request aborted." In source of this website I realised that is missing. This is part of view-source from my site:
<div style="margin-left:35%;margin-right:35%;">
<fieldset>
<legend> Wszystkie pola oprócz numeru telefonu należy wypełnić </legend>
<form method="post" action=".">
<p><label for="id_username">Login:</label> <input id="id_username" maxlength="30" name="username" type="text" required/></p>
<p><label for="id_email">Email:</label> <input id="id_email" name="email" type="email" required /></p>
<p><label for="id_password1">Hasło:</label> <input id="id_password1" name="password1" type="password" required /></p>
<p><label for="id_password2">Powtórz hasło:</label> <input id="id_password2" name="password2" type="password" required /></p>
<p><label for="id_phone">Telefon:</label> <input id="id_phone" maxlength="20" name="phone" type="text" /></p>
<p><label for="id_log_on">Logowanie po rejestracji:</label><input id="id_log_on" name="log_on" type="checkbox" /></p>
<input type="submit" value="Rejestracja"><input type="reset" value="Wartości początkowe">
</form>
</fieldset>
</div>
I was surprised of that, because in my files on Pythonanythere this fragment of code is present.
This is part of my file register.html on Pythonanythere:
<div style="margin-left:35%;margin-right:35%;">
<fieldset>
<legend> Wszystkie pola oprócz numeru telefonu należy wypełnić </legend>
<form method="post" action=".">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Rejestracja"><input type="reset" value="Wartości początkowe">
</form>
</fieldset>
</div>
What am I doing wrong that my webpage don't see this piece of code? It is seamed on server but on webpage view-source It isn't.
EDIT:
This is view, which render my template:
def register(request):
if request.method == 'POST':
form = FormularzRejestracji(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
user.last_name = form.cleaned_data['phone']
user.save()
if form.cleaned_data['log_on']:
user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'])
login(request, user)
template = get_template("osnowa_app/point_list.html")
variables = RequestContext(request, {'user': user})
output = template.render(variables)
return HttpResponseRedirect("/")
else:
template = get_template("osnowa_app/register_success.html")
variables = RequestContext(request, {'username': form.cleaned_data['username']})
output = template.render(variables)
return HttpResponse(output)
else:
form = FormularzRejestracji()
template = get_template("osnowa_app/register.html")
form = FormularzRejestracji()
variables = RequestContext(request, {'form': form})
output = template.render(variables)
return HttpResponse(output)
You should pass a plain dict and the request object to template.render(), not a RequestContext. The template engine will convert it to a RequestContext for you:
template = get_template("osnowa_app/register.html")
context = {'form': form}
output = template.render(context, request)
Right now, the template.render() function sees a dict-like object as the first argument, but no request as the second argument. Without a request as the second argument, it converts the dict-like RequestContext into a plain Context object. Since the Context object doesn't run context processors, your context is missing the csrf token.
Alternatively you can just use the render shortcut, which returns a HttpResponse object with the rendered template as content:
from django.shortcuts import render
def register(request):
...
return render(request, "osnowa_app/register.html", {'form': form})
This particular case is also being discussed in ticket #27258.
CSRF token gets included in HTML form by calling hidden_tag function on your form object.
For example check this gist, line number 6. This is how you add form and it's elements in jinja.
I am trying to print off the checkbox value in Flask when I hit the submit button.
app.py snippet:
#app.route('/test2', methods=['GET', 'POST'])
def test2():
if request.method == "POST":
if request.form['submit'] == 'submit':
print(request.args.get('check'))
return render_template('test.html')
HTML:
<div class="container"><br>
<form role="form" method="post">
<input type="checkbox" name="check" value="test">
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</div>
It returns 'None' when I hit the submit button.
I have also tried request.form.get()
#app.route('/test2', methods=['GET', 'POST'])
def test2():
if request.method == "POST":
if request.form['submit'] == 'submit':
print(request.form.get('check'))
return render_template('test.html')
That also returns 'None'.
When submitting an HTML form, unchecked checkboxes do not send any data. On Flask's side, there will not be a key in form, since no value was received. If you want to check if a single checkbox (with a unique name) is checked, just test if it's name is in form. If you want to check which of multiple checkboxes (with the same name, but different values) are checked, use getlist instead.
One boolean:
<input type="checkbox" name="check">
checked = 'check' in request.form
Multiple options:
<input type="checkbox" name="check" value="1">
<input type="checkbox" name="check" value="2">
<input type="checkbox" name="check" value="3">
selected = request.form.getlist('check')
any_selected = bool(selected)
I'm currently working on a fairly simple django project and could use some help. Its just a simple database query front end.
Currently I am stuck on refining the search using checkboxes, radio buttons etc
The issue I'm having is figuring out how to know when a checkbox (or multiple) is selected. My code so far is as such:
views.py
def search(request):
if 'q' in request.GET:
q = request.GET['q']
if not q:
error = True;
elif len(q) > 22:
error = True;
else:
sequence = Targets.objects.filter(gene__icontains=q)
request.session[key] = pickle.dumps(sequence.query)
return render(request, 'result.html', {'sequence' : sequence, 'query' : q, 'error' : False})
return render(request, 'search.html', {'error': True})
search.html
<p>This is a test site</p></center>
<hr>
<center>
{% if error == true %}
<p><font color="red">Please enter a valid search term</p>
{% endif %}
<form action="" method="get">
<input type="text" name="q">
<input type="submit" value="Search"><br>
</form>
<form action="" method="post">
<input type='radio' name='locationbox' id='l_box1'> Display Location
<input type='radio' name='displaybox' id='d_box2'> Display Direction
</form>
</center>
My current idea is that I check which checkboxes/radio buttons are selected and depending which are, the right data will be queried and displayed in a table.
So specifically:
How do I check if specific check-boxes are checked? and how do I pass this information onto views.py
Radio Buttons:
In the HTML for your radio buttons, you need all related radio inputs to share the same name, have a predefined "value" attribute, and optimally, have a surrounding label tag, like this:
<form action="" method="post">
<label for="l_box1"><input type="radio" name="display_type" value="locationbox" id="l_box1">Display Location</label>
<label for="d_box2"><input type="radio" name="display_type" value="displaybox" id="d_box2"> Display Direction</label>
</form>
Then in your view, you can look up which was selected by checking for the shared "name" attribute in the POST data. It's value will be the associated "value" attribute of the HTML input tag:
# views.py
def my_view(request):
...
if request.method == "POST":
display_type = request.POST.get("display_type", None)
if display_type in ["locationbox", "displaybox"]:
# Handle whichever was selected here
# But, this is not the best way to do it. See below...
That works, but it requires manual checks. It's better to create a Django form first. Then Django will do those checks for you:
forms.py:
from django import forms
DISPLAY_CHOICES = (
("locationbox", "Display Location"),
("displaybox", "Display Direction")
)
class MyForm(forms.Form):
display_type = forms.ChoiceField(widget=forms.RadioSelect, choices=DISPLAY_CHOICES)
your_template.html:
<form action="" method="post">
{# This will display the radio button HTML for you #}
{{ form.as_p }}
{# You'll need a submit button or similar here to actually send the form #}
</form>
views.py:
from .forms import MyForm
from django.shortcuts import render
def my_view(request):
...
form = MyForm(request.POST or None)
if request.method == "POST":
# Have Django validate the form for you
if form.is_valid():
# The "display_type" key is now guaranteed to exist and
# guaranteed to be "displaybox" or "locationbox"
display_type = request.POST["display_type"]
...
# This will display the blank form for a GET request
# or show the errors on a POSTed form that was invalid
return render(request, 'your_template.html', {'form': form})
Checkboxes:
Checkboxes work like this:
forms.py:
class MyForm(forms.Form):
# For BooleanFields, required=False means that Django's validation
# will accept a checked or unchecked value, while required=True
# will validate that the user MUST check the box.
something_truthy = forms.BooleanField(required=False)
views.py:
def my_view(request):
...
form = MyForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
...
if request.POST["something_truthy"]:
# Checkbox was checked
...
Further reading:
https://docs.djangoproject.com/en/1.8/ref/forms/fields/#choicefield
https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#radioselect
https://docs.djangoproject.com/en/1.8/ref/forms/fields/#booleanfield
In models :
class Tag:
published = BooleanField()
(...)
In the template:
{% for tag in tags %}
<label class="checkbox">
<input type="checkbox" name="tag[]" value="" {% if tag.published %}checked{% endif %}>
</label>
{% endfor %}
Assuming you are sending the form as a POST, the values of the selected checkboxes are in request.POST.getlist('tag').
For example :
<input type="checkbox" name="tag[]" value="1" />
<input type="checkbox" name="tag[]" value="2" />
<input type="checkbox" name="tag[]" value="3" />
<input type="checkbox" name="tag[]" value="4" />
Say if 1,4 were checked,
check_values = request.POST.getlist('tag')
check_values will contain [1,4] (those values that were checked)
{% for tag in tags %}
<label class="checkbox">
<input type="checkbox" name="tag[]" value=""
{% if tag.published %}checked{% endif %}>
</label>
{% endfor %}
<input type="checkbox" name="tag[]" value="1" />
<input type="checkbox" name="tag[]" value="2" />
<input type="checkbox" name="tag[]" value="3" />
<input type="checkbox" name="tag[]" value="4" />