Select several input files Python Flask application - python

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.

Related

HTML button onclick action with Django function

HTML form on Django.
I want to perform or create web page in which the button performs the action, and in backend I am handling the Django function.
The code of HTML file is:
<form name="bookappointment" class="form" method="POST">
{% csrf_token %}
<br>
<input type="hidden", name="selecteddoctornumber" value="{{i.doctornumber}}">
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-4">
<button class="btn approve" name="approvebtn">Approved</button>
</div>
<div class="col-md-1"></div>
<div class="col-md-4">
<button class="btn notapprove" name="notapprovebtn">Not Approved</button>
</div>
<br>
</div>
<a class="btn cancel" href="requests">Cancel</a>
<br>
</form>
and the other side the Django function is:
if request.method == 'POST':
if request.POST.get('approvebtn'):
for i in doctor:
if pendingDoctorNumber == i.contactNumber:
i.status = 'Approved'
return redirect('request')
if request.POST.get('notapprovebtn'):
for i in doctor:
if pendingDoctorNumber == i.contactNumber:
i.status = 'Not Approved'
return redirect('request')
but its not working any action just get me back to same page
<form action="{% url 'bookappointment' %}" method="POST">
you have to define bookappointment in your urls.py which redirect to views.py where your function lies with name bookappointment.

Flask request.form[] not pulling data

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' }}">

Uploading two files in single page in django

I am new to django.I want to upload two files in single page.I have created form for uploading one file.But with same code I have tried upload two files by making some changes.But I can't get it .
Please help me to submitting two files in one submit button in a single page
views.py
from __future__ import unicode_literals
from django.shortcuts import render
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.conf.urls import url
#import csv
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
#request.FILES['myfile'] and request.FILES["myfile1"]:
myfile = request.FILES['myfile']
#myfile1=request.FILES["myfile1"]
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
#filename1=fs.save(myfile1.name, myfile1)
uploaded_file_url = fs.url(filename)
#uploaded_file_url1 = fs.url(filename1)
#data = [row for row in csv.reader(myfile.read().splitlines())]
return render(request, 'myapp/simple_upload.html', {
'uploaded_file_url': uploaded_file_url,
})
#upload_file = request.FILES['upload_file']
#data = [row for row in csv.reader(upload_file.read().splitlines())]
return render(request, 'myapp/simple_upload.html')
def home(request):
return render(request,'myapp/home.html')
html
<!doctype>
<html>
{% block content %}
<body>
<div class="col-md-12">
<form action="{% url "home" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<label for="fileupload" class="btn btn-primary col-md-2 col-sm-4 uploadBtn" >Upload GSTR 2A</label><br>
<input type="file" class="fileupload" id="fileupload" name="myfile" required="True">
</div>
<div class="col-md-1 col-sm-2" style="text-align:center">
<i class="fa fa-check-circle checkIcon"></i>
</div>
<div class="col-md-1 col-sm-2">
<p class="cancel">X</p>
</div>
</div>
<div class="col-md-12">
<form action="{% url "home" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<label for="fileupload" class="btn btn-primary col-md-2 uploadBtn" >Upload Purchase Account</label><br>
<input type="file" class="fileupload" id="fileupload" name="myfile" required="True" >
<div class="col-md-1">
<a"<p class="cancel">X</p><a>
</div>
</div>
<div class="buttonGroup">
<button type="submit" class="btn btn-primary recBtn">Reconcile</button> <span class="backBtn"> Back</span>
</div>
</form>
</div>
{% endblock %}
</body>
</html>
You only need to have two type file inputs inside the form, and get it in the view exactly like the first you created, like this:
<form method="post" enctype="multipart/form-data" required="True">
{% csrf_token %}
<input type="file" name="myfile">
<input type="file" name="myfile2">
<button type="submit">Upload</button>
</form>
and in your views, you get it and save it like the first one:
myfile = request.FILES['myfile']
myfile2 = request.FILES['myfile2']
In case you need to add the input file outsite the form, you need to add the "form" attribute to the input file. like this:
<input type="file" name="myfile2" form="FORM_ID">
just replace FORM_ID with the id of your form.

Bad Request with Flask

really struggling with this bad request from flask. I know normally it caused by flask not finding the [key] in the form.. However, I've checked my form and python code 40 times and cannot see any reason that would be the case.. I have commented out each line of the python code that references request.form. I have done it 1 by 1 and I still get a bad request. However when I comment out all the lines the bad request goes away.. Any thought would be wonderful..
Python code;
if request.method == 'POST':
form = 'Add Package Form'
clientId = request.form['id']
date = request.form['date2']
strPrice = request.form['price']
price = float(strPrice)
adultlessons = request.form['adult']
juniorlessons = request.form['junior']
shortlessons = request.form['short']
playinglessons = request.form['playing']
notes = request.form['notes']
form..
<form action="/addpackage" method="post" class="sky-form">
<fieldset>
<section>
<label class="label">Select Package Date</label>
<label class="input">
<i class="icon-append fa fa-calendar"></i>
<input type="text" name="date2" id="date">
</label>
</section>
<div style="margin: -25px"></div>
<fieldset>
<section>
<label class="label">Price</label>
<label class="input">
<input type="text" name="price">
</label>
</section>
<section>
<label class="label">Adult Lessons</label>
<label class="input">
<input type="text" name="adult">
</label>
</section>
<section>
<label class="label">Junior Lessons</label>
<label class="input">
<input type="text" name="junior">
</label>
</section>
<section>
<label class="label">Short Game Lessons</label>
<label class="input">
<input type="text" name="short">
</label>
</section>
<section>
<label class="label">Playing Lessons</label>
<label class="input">
<input type="text" name="playing">
</label>
</section>
<section>
<label class="label">Notes</label>
<label class="textarea textarea-expandable">
<textarea rows="3" name="notes"></textarea>
</label>
<div class="note"><strong>Note:</strong> expands on focus.</div>
</section>
</fieldset>
</fieldset>
<!-- hidden client id -->
<input type="hidden" name="id" value="{{ client.id }}">
<!-- /hidden client id -->
<footer>
<button type="submit" name="addpackage" value="package" class="button">Add Package</button>
</footer>
</form>
This is something of a half-answer, but it was too long for a comment.
If you enable debugging in your Flask app you should get a detailed traceback indicating exactly where the problem is occurring (both in the browser and on your console).
If your application currently has something like:
app.run()
Just set the debug parameter to true:
app.run(debug=True)
If after enabling debugging you're still not sure what's causing the problem, update your question to include the traceback.
For what it's worth, if I dump your form and your code into a simple Flask app, it all seems to work just fine as long as I provide a numeric value for the price field.
Usually you'll get a 400 Bad Request in Flask while submitting a form when you try and access a form key in the request object that doesn't exist.
This is because the request.form object inherits its __getitem__ method the Multidict class in the werkzeug.datastructures module which raises a BadRequestKeyError when a key doesn't exist.
You should give the form data a default value to avoid HTTP 400 error, like this:
default_value = True
is_public = request.form.get('public', default_value)
However, I recommend you to use Flask-WTF.
With Flask-WTF, your code can be simplify to this (an example):
import ...
app = Flask(__name__)
class EditProfileForm(Form):
name = StringField('name', validators=[Length(0, 64)])
location = StringField('city', validators=[Length(0,64)])
website = StringField('website', validators=[Length(0,64), render_kw={"placeholder": "http://..."})
about_me = TextAreaField('Bio', validators=[Length(0,2000)], render_kw={"placeholder": "I'm......"})
submit = SubmitField(u'submit')
#app.route('/edit-profile', methods=['GET', 'POST'])
def edit_profile():
form = EditProfileForm()
if form.validate_on_submit():
current_user.name = form.name.data
current_user.location = form.location.data
current_user.website = form.website.data
current_user.about_me = form.about_me.data
db.session.add(current_user)
flash('Update success!', 'success')
return redirect(url_for('.user', username=current_user.username))
return render_template('edit_profile.html', form=form)
In your html file:
<form method="POST" action="/">
{{ form.hidden_tag() }}
{{ form.name.label }} {{ form.name() }}
{{ form.location.label }} {{ form.location() }}
...
</form>
By the way, if you use Flask-Bootstrap, you can just use one line to render the whole form:
{% import "bootstrap/wtf.html" as wtf %}
{{ wtf.quick_form(form) }}
I hope it will help.

django read file for importing details

I have used django-adaptops for this purpose. i have implemented the mechanism shown in docs. I need to know how can achieve this using browser , for example - i have a template where user has the option to select the csv file, once i click the import button i get the call to my view , but here i cannot read the file to upload to my model. how i can perform this.
this is my template code.
<form action="/manage/dashboard/importProspects" method="post" class="form-horizontal"
enctype="multipart/form-data"> {% csrf_token %}
<div class="row-fluid" style="margin-top: 5%">
<div class="span6">
<div class="control-group">
<p>{{ csvform.fname.label_tag }} {{ csvform.fname }} {{ csvform.fname.url }}</p>
</div>
</div>
<button type="submit" class="btn btn-small btn-success " style="margin-left:10px; ">
Import from CSV
</button>
</div>
</form>
csvForm is form object passed when this template is loaded.
the form code is below:
class ImportCsvForm(forms.Form):
fname = forms.FileField(label='CSV')
and /manage/dashboard/importProspects url will call my view importcsv which right now does not perform anything.
how can i handle this so that i can read the csv file, i cannot get the csvfile path. or am i missing some thing here ? please help.
Follow this,
in template:
<form action="/manage/dashboard/importProspects" method="post" class="form-horizontal"
enctype="multipart/form-data"> {% csrf_token %}
<div class="row-fluid" style="margin-top: 5%">
<div class="span6">
<div class="control-group">
<p>
<input type="file" name="csvfile" />
</p>
</div>
</div>
<input type="submit" class="btn btn-small btn-success " style="margin-left:10px; " />
</div>
</form>
in urls.py:
urlpatterns = patterns("mine.views",
url(r'^', 'csvupload'),)
in views.py file:
def csvupload(request):
if request.method == "POST":
f = request.FILES['csvfile']
with open("/tmp/csvfile.csv", 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
then use csvfile whatever you want.....Hope this helps to you.

Categories

Resources