I am trying to spin first Django project and I am struggling how to pass value to python function from html. Basically, I have 1 placeholder with 3 buttons next to it.
I have file.html in templates.
<form method="POST" action="">
{% csrf_token %}
<input type="text" name="name_id" placeholder="placeholder value"/>
<input type="submit" value="Value 1"/>
<input type="submit" value="Value 2"/>
<input type="submit" value="Value 3"/>
</form>
I am trying to pass placeholder value to views.py. In views.py I have 3 functions. I want to execute only one of them based on value.
Value 1 from file html triggers function 1 in views py
Value 2 from file html triggers function 2 in views py
Value 3 from file html triggers function 3 in views py
I am not sure how to handle urls.py
All files are in same app/folder
Any help is much appreciated.
You can work with a name="…" attribute on the submit <button>s:
<form method="POST" action="">
{% csrf_token %}
<input type="text" name="name_id" placeholder="placeholder value"/>
<input type="submit" name="value1"/>
<input type="submit" name="value2"/>
<input type="submit" name="value3"/>
</form>
In the view you can then check with:
def some_view(request):
if request.method == 'POST':
if 'value1' in request.POST:
# …
pass
elif 'value2' in request.POST:
# …
pass
elif 'value3' in request.POST:
# …
pass
Related
I am trying to develop some basic django templates where i initially pass the django template variable which is an array - {{array_list}}. I am able to perform operations on this dtv easily. But I am unable to post this variable back to views.
Eg. I pass {'array_list': [1,2,3,4]}
<form action="some_action" method="post">
{% csrf_token %}
<input type="submit" value="sort">
<input type="hidden" name="array_list" value={{array_list}}>
</form>
And in views.py:
array_list = request.POST['array_list']
return render(request, 'result.html', {'array_list': array_list})
But i don't get the full array back to result.html, and i only get [1, as the array_list.
Probably you can do something like this:
First, use join tag to turn that list into comma separated string.
<form action="some_action" method="post">
{% csrf_token %}
<input type="submit" value="sort">
<input type="hidden" name="array_list" value='{{array_list|join:","}}'>
</form>
And get the value in POST request and split it by ,.
array_list = request.POST['array_list'].split(',')
I'm looking to create a Django form with a checkbox.Irrespective of weather I check or uncheck the box,it is not detected in POST request.Here is the code of the template-
<form action="annotate_page" method="post">{% csrf_token %}
<input id="repeat" type="checkbox" >
<label for="repeat">Repeat Sentence?</label>
<br>
<button type="submit">Next</button><br>
</form>
Here is my forms.py-
from django import forms
class AnnotateForm(forms.Form):
repeat=forms.BooleanField(required=False)
Here is my views logic-
if request.method=="POST":
form = AnnotateForm(request.POST)
if form.is_valid():
print(request.POST)#prints only csrf_token in Query_dict
print(form.cleaned_data["repeat"])#Always false
Irrespective of weather the checkbox is checked or not,the print statement always gives False.
I know there are questions similar,but they don't solve my problem.
<form action="annotate_page" method="post">{% csrf_token %}
<input id="repeat" name="something" type="checkbox" >
<label for="repeat">Repeat Sentence?</label>
<br>
<button type="submit">Next</button><br>
</form>
and in view
if request.method=="POST":
form = AnnotateForm(request.POST)
if form.is_valid():
print(request.POST)#prints only csrf_token in Query_dict
print(form.cleaned_data["something"])#Always false
you need to give a name in the input field or else it wont be captured
First of all sorry if that's a silly question, but I am kind of stuck..
I want to pass a couple of variables from my HTML/Bootstrap page to Flask. The variables are obtained in a form.
The variable is to be selected from a dropdown. Once the variable is selected from mySQL2 it should be stored in customername.
At the moment I've got this sample code which does not work at all.
<form action="" class="form-group" method="post">
<div class="form-group">
<label for="selectcustomer">Select your customer</label>
<input
<select class="form-control" id="selectcustomer">
{% for j in mySQL2 %}
<option>{{j[2]}}</option>
{% endfor %}
</select> value="{{request.form.customername}}">
<input type="text" class="form-control" name="customername" value="{{request.form.customername}}">
</div>
<br>
<input class="btn btn-default" type="submit" value="Submit">
</form>
How can I post the selected value into customername?
The form looks like this:
I need the selection field to be a dropdown. Once a value is selected it should be stored in customername.
Before form submission can't get the submit values. To get posted data in view use:
request.form["selectcustomer"]
note: html select tag should have a name attribute <select name="selectcustomer" ...> so you can get value with name not the select id.
Lets say you have a view as follows:
def customer():
customername = ""
if request.method == 'POST':
customername = request.form["customername"]
return render_template("yourhtmlfile", customername=customername)
#yourhtml
...
{{customername}}
I have in my template:
This is passed by {{form}}
<form action="" method="POST">
Inicio: <input type="text" id="start">
<input type="submit" value="Sned" >
{% csrf_token %}
</form>
Then in the views.py
def test(request):
if request.method != 'POST':
context = {'form': 'by GET'}
return render(request, 'test.html', context)
else:
if 'start' in request.POST:
start = request.POST['start']
else:
start = False
context = {'form': start}
return render(request, 'test.html', context)
It seems that always return False
If I dont check the existance of the key I have this error:
MultiValueDictKeyError
And the erropage says : "'start'" (single plus double quotes)
id is intended for javascript and css purposes. For variables that are important on server side, you should use name tag.
<input type="text" id="start" name="start">
You need to add a name attribute in your input, so when you are getting the POST data it will be found.
<form action="" method="POST">
Inicio: <input type="text" id="start" name="start">
<input type="submit" value="Sned" >
{% csrf_token %}
</form>
Also I recommend you to do the following change in your view:
Replace
request.POST['start']
by:
request.POST.get('start')
So, if the field is not found, it will be reassigned whith a None value.
add name
<input type="text" name="start" id="start">
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" />