I am trying to pass a value to my view using a form as follows,
I have the following form:
<form action="{% url 'searchlocation' %}" method="get">
{% csrf_token %}
<input type="text" class="form-control" id="search_location" placeholder="Search">
<span class="input-group-btn">
<button type="submit" class="btn btn-danger"><i class="fa fa-search"></i>
</button>
</span>
</form>
and in my view i have:
def SearchLocation(request):
if request.method == 'GET':
keyword = request.GET.get('search_location','')
print keyword
return render_to_response('app/location.html', {'user': request.user}, RequestContext(request))
I am not getting any value for keyword here. It just gives me a ''.
When i tried request.GET['search_location'], it gave me a multivaluedict error.
You must supply a name for your form input in order for it to be sent by the browser, like so:
<input type="text" name="search_location" class="form-control" id="search_location" placeholder="Search">
Request data is sent in the form of a key/value pair. With no name attribute, there is no key for the value and the input is not sent by the browser.
Related
In my django project I have a page displaying a list of times. On this page there is 3 GET forms which are for:
Parsing through pages
Selecting graph data
Sorting items
If a user is to select a field in all of these forms the URL should look something like this:
http://127.0.0.1:8000/watchlist/?page=1&graph_data=price&sort=quantity_desc
But when a user submits one of these forms it only saves that GET parameter in the URL. eg:
selects page = 2
http://127.0.0.1:8000/watchlist/?page=2
selects sort = quantity_asc
http://127.0.0.1:8000/watchlist/?sort=quantity_asc
The page parameter is over written when both parameters should be present in the URL. How can i preserve multiple GET parameters in the URL?
views.py
def watchlist(request):
#get requests
graph_metric = request.GET.get("graph-data-options", "avg_price")
page = int(request.GET.get("page", 1))
sort_field = request.GET.get("sort-field", "avg_price-asc")
return render(request, "App/watchlist.html", context=context)
html
<!-- Page number -->
<form id="page-buttons-form" action="{% url 'watchlist' %}" method="GET">
{% for page_button in num_pages %}
<input name="page" type="submit" value="{{page_button}}">
{% endfor %}
</form>
<!-- Sort items -->
<form id="sort-form" action="{% url 'watchlist' %}" method="GET">
<label for="sort-field">Sort:</label>
<select onchange="this.form.submit()" name="sort-field">
{% for sort in sort_options %}
<option value="{{sort.value}}">{{sort.text}}</option>
{% endfor %}
</select>
</form>
<!-- Graph data -->
<form action="{% url 'watchlist' %}" method="GET">
<label for="graph-data-options">Graph Data</label>
<select onchange="this.form.submit()" name="graph-data-options">
{% for graph_option in graph_options %}
<option value="{{graph_option.value}}">{{graph_option.text}}</option>
{% endfor %}
</select>
</form>
This is a proof of concept to demonstrate how you can preserve GET parameters when submitting different forms. Each form runs a function fillHiddenFields before submitting, inserting existing URL parameters into the hidden fields.
Note: Apparently this does not work as a StackOverflow snippet, so you'll have to run this on your local machine.
function fillHiddenFields(event){
// extract query params from URL
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
// find hidden fields in form
let form = event.target;
const hiddentElmts = form.querySelectorAll('input[type=hidden]');
// update hidden fields with URL query params
for(let elmt of hiddentElmts){
if(elmt.name in params){
elmt.value = params[elmt.name];
}
}
// console.log form data to check that hidden fields are updated
let formdata = new FormData(form);
console.log(Object.fromEntries(formdata));
}
<body>
<form id="form1" action="javascript:void(0)" method="GET" onsubmit="fillHiddenFields(event)">
<input type="text" name="field1" value="Field 1">
<input type="hidden" name="field2" value="">
<input type="submit" value="Submit">
</form>
<form id="form2" action="javascript:void(0)" method="GET" onsubmit="fillHiddenFields(event)">
<input type="hidden" name="field1" value="">
<input type="text" name="field2" value="Field 2">
<input type="submit" value="Submit">
</form>
</body>
I am trying to post a simple html form and pull the data into python/flask. request.form does not appear to be pulling my form data.
I have a function created to pull the variables if the request method is POST, but the URL ends up with the variables being blank. See code below
#app.route('/inquire',methods=['POST','GET'])
def inquire():
if request.method == 'POST':
name = request.form['dname']
email = request.form['demail']
message = request.form['dmessage']
return
redirect(url_for('inquire_success',name=name,email=email,message=message))
return render_template('inquire.html')
#app.route('/inquiresuccess/',methods=['POST','GET'])
def inquire_success(name,email,message):
return render_template('inquiresuccess.html',name=name,email=email,message=message)
the html below :
<div class="container">
<div class="main">
<form method="post" class="form" action="{{
url_for('inquire_success' }}">
<h2>Inquire below and we'll get back to you</h2>
<label>Name :</label>
<input type="text" name="dname" id="dname" value="name">
<label>Email :</label>
<input type="text" name="demail" id="demail" value="email">
<label>Project info :</label>
<textarea class="messagebox" name="dmessage" id="dmessage"
value="message">
</textarea>
<input type="submit" name="submit" id="submit" value=Submit>
</form>
I would like the code to redirect me to inquiresuccess.html with the variables displayed. Thanks for any help.
The form looks to be posting to the wrong endpoint. Try changing
<form method="post" class="form" action="{{ url_for('inquire_success' }}">
to
<form method="post" class="form" action="{{ url_for('inquire' }}">
I want to select several input files in my flask application, when I want to have an array list of my selected input files, the array is empty. How can I fix that ?
HTML
<form method="POST">
<div class="form-group">
<h6>Select files:</h6> <input type="file" name="inputfiles[]" multiple=""><br><br>
</div>
<div class=" form-group">
<button type="submit" class="btn btn-light text-primary" >GO</button>
</div>
</form>
Python
#app.route('/gp_bagging_several_apps', methods=['POST','GET'])
def gp_bagging_several_apps():
if request.method == 'POST':
print("HELLO")
f = request.files.getlist("inputfiles[]")
print(f)
I also tried with "inputfiles" instead of "insteadfiles[]". I had the same problem.
Thank you
I think in your input tag, you should have multiple. In your form tag, have action and enctype.
You can try something like below:
<form action="{% url 'function' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p><input type="file" name="files" required multiple/></p>
<p><input type="submit" value="Upload" class="btn btn-primary btn-large"/></p>
</form>
And in the function:
if request.method == 'POST':
files = request.FILES.getlist('files')
for file in files:
# process your file
Let me know if it works.
This question already has an answer here:
CSRF token missing or incorrect, even after including the token tag
(1 answer)
Closed 5 years ago.
POST requests to the Django view below result in (403) CSRF verification failed. I've confirmed that the hidden csrf token gets rendered in the page's source. I am also able to make POST requests without errors in other views. I'm unsure how to debug further.
views.py:
def email(request):
if request.method == 'POST':
email = request.POST['email']
fd = open('emaildb.csv','a')
fd.write(email+',somefile\n')
fd.close()
return render(request, 'receipts/email.html', {'text':'Thanks, we''ll get back to you soon.'})
else:
return render(request, 'receipts/email.html',)
email.html:
<form action="email" method="post" enctype="text/plain">
{% csrf_token %}
E-mail:<br>
<input type="text" name="email">
<input type="submit" value="Send">
</form>
U can't call method like that
<form action="email" method="post" enctype="text/plain">
{% csrf_token %}
E-mail:<br>
<input type="text" name="email">
<input type="submit" value="Send">
</form>
in your urls.py u must write
url(r'^email/$', views.email, name='email')
and call this method using form like that
<form action="{% url 'your_folder_name_where_located_your_urls.py:email'%}" method="post" enctype="text/plain">
{% csrf_token %}
E-mail:<br>
<input type="text" name="email">
<input type="submit" value="Send">
</form>
I am trying to submit a form through python and I send a urllib request with a url like
https://example.com/form_submitted?element_1=data
It worked on another form but this one contains onsubmit attribute in the form tag and it only redirects me to the form page with the input field filled with data and if I click the submit button, it works.
I also tried https://example.com/form_submitted?element_1=data&submit=Submit but it didn't work. What can I do?
<form id="form_1" method="post" action="form_submitted" onsubmit>
<label for="element_1">Text</label>
<div>
<input id="element_1" name="element_1" type="text" maxlength="255" value=""/>
</div>
<input id="saveForm" type="submit" name="submit" value="Submit" />
</form>