Trying to upload multiple files at once using python. The upload.html source code is as followed:
<form name="frmRegister" method="post" accept-charset="utf-8" enctype="multipart/form-data" class="form-horizontal">
<div class="control-group">
<div class="controls">
<input type="file" name="files" multiple='multiple'>
</div>
</div>
<div class="control-group">
<div class="controls">
<input class="btn btn-primary" type="submit" name="btnSubmit" value="Add Product" />
</div>
</div>
</form>
in my admin.py:
#view_config(context="mycart:resources.Product", name="add", renderer='admin/mall/product/add.jinja2', permission = 'admin')
#view_config(context="mycart:resources.Product", name="add", request_method="POST", renderer='admin/mall/product/add.jinja2', permission = 'admin')
def product_add(context, request):
if 'btnSubmit' in request.POST:
print ("files >>> ", request.POST['files'])
in my terminal, it is showing just FieldStorage('files', u'DSC01973.JPG') whereas I've selected 'DSC01975.JPG', 'DSC01976.JPG'.
Why is this so?
I've found a way to solve it, I believe there are many others, if there are, please feel free to holler out:
fileslist = request.POST.getall('files')
print ("My files listing: ", fileslist)
for f in fileslist:
print ( "individual files: ", f )
I could solve the problem with the following function:
from cgi import FieldStorage
def get_all_file_data_list(request):
return [x for x in request.POST.values() if isinstance(x, FieldStorage)]
Related
I need to get data from a bootstrap modal input. I'am using the following code :
#app.route('/rejets_modeles', methods=("POST","GET"))
def rejets_modeles():
{code}
if request.method == 'POST':
uname = request.form['uname']
print("----")
print(uname)
return render_template ('rejets_modeles.html', tables=[df.to_html(table_id = 'rejets_modeles')], titles=df.columns.values, header="true")
And here is my HTML code
<form action="POST">
<div class="modal-body-modifs">
<p>Gestion du rejet : </p>
<label><b>NOM</b></label>
<input type="text" name="uname"></br>
<label><b>PRENOM</b></label>
<input type="text" name="uprenom"></br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-default" data-dismiss="modal"> OK</button>
</div>
</form>
I don't even have the ("---") printed, that means that my 'POST' request isnt' interpreted. How can I fix that ? Thank you
It has to be method instead of action
<form method="POST">
In action you can set url to which it has to send form data - ie.
<form method="POST" action="/rejets_modeles">
but if you want to send to the same url then you don't have to set it.
Solved. The problem was data-dismiss="modal" in my input tag. If you delete this the modal will close and the form will be sent via POST request.
screenshot of the outputI'm looking to get posts from a user to post on individual lines. At the moment I take in a name, email and comment, pass it to the app.py file and store it to a text file. I return a name, email, comment and the time of the comment. When I read the file and pass in back to the html template the posts display one after the other (see the screenshot included), and im trying to have them display one below each other. f.write("\n") results in the actual text file skipping a line however this does not occur in the template.
form_action.html
<html>
<div align = "center">
<body style="background-color: #3DC247;">
<head>
<title>Conor McGregor</title>
</head>
<body>
<div align = "center">
<h1 style="font-family:verdana;">I AM EL CHAPO</h1>
<div align = "center">
<h2 style="font-family:verdana;">YOU'LL DO NUTIN.</h2>
<div align = "center">
<h2 style="font-family:verdana;">Disscusion Page</h2>
<body>
<div id="container">
<div class="title">
<h3 style="font-family:verdana;">Please fill in your details
below and your comment to join the discussion</h3>
</div>
<div id="content">
<form method="post" action="{{ url_for('hello') }}">
<label for="yourname" style="font-family:verdana;">Please
enter your name:</label>
<input type="text" name="yourname" /><br /><br>
<label for="youremail" style="font-family:verdana;">Please
enter your email:</label>
<input type="text" name="youremail" /><br /><br>
<label for="yourcomment"style="font-family:verdana;">Please
enter your comment:</label>
<input type="textarea" name="yourcomment" rows="4" cols="50">
<input type="submit" /><br>
</form>
</div>
</div>
</div>
</div>
<div id="container">
<div class="title">
<h1 style="font-family:verdana;"><p>Comments</p></h1>
</div>
<div id="content">
{{details}}
</div>
</div>
</body>
</html>
app.py
from flask import Flask, render_template, request, url_for
import time
import datetime
# Initialize the Flask application
app = Flask(__name__)
# Define a route for the default URL, which loads the form
#app.route('/')
def form():
return render_template('form_submit.html')
#app.route('/hello/', methods=['POST','GET'])
def hello():
global time
name=request.form['yourname']
email=request.form['youremail']
comment=request.form['yourcomment']
comment_time=time.strftime("%a-%d-%m-%Y %H:%M:%S")
f = open ("user+comments.txt","a")
f.write(name + ' ' + email + ' ' + comment + " " + comment_time)
f.write('\n')
f.close()
with open("user+comments.txt", "r") as f:
details = f.read()
f.close()
return render_template('form_action.html', details = details, name=name,
email=email, comment=comment, comment_time=comment_time)
if __name__ == '__main__':
app.run(debug=True)
HTML does not know what \n is. You can fix this in two ways.
Convert str details to list details
details = f.read().split('\n')
This converts the str object to list object. You could print it in your template using
{% for detail in details %}
{{detail}}
{% endfor %}
Replace \n with <br>
details = f.read().replace('\n','<br>')
and then print it as {{ details|safe }} in form_action.html.
It is important that you use the safe filter. The <br> would be escaped without it and rendered as simple text.
I want to upload an image to twitter taken by a django form:
<div class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title">Panel title</h3>
</div>
<div class="panel-body">
<form action="" method="POST" role="form" enctype="multipart/form-data">
{% csrf_token %}
<legend>Upload a file: </legend>
<div class="form-group">
<input type="file" name="file" class="form-control" id="">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
The image I got is:
if fileForm.is_valid():
print "file is uploaded."
paramFile = open(request.FILES['file'],'rb')
# paramFile = request.FILES['file'].read()
api.update_with_media(paramFile,status="Hello first image")
The error I got is:
coercing to Unicode: need string or buffer, InMemoryUploadedFile found
How can I upload this to twitter?
Method update_with_media() has only one positional argument which takes filename.
So you can specify filename something like this:
api.update_with_media(request.FILES['file'].name,
status="Hello first image")
Also you should pass file using keyword argument 'file':
api.update_with_media(request.FILES['file'].name,
file=request.FILES['file'],
status="Hello first image")
As per docs, you have to pass both file parameter which will be opened internally and filename parameter which is needed to determine MIME type and will be used to as form field in post data. So just pass them explicitly as keyword arguments and you should be fine.
I tried to upload two files woth two different location but when uploading files, I'm getting this error "ValueError: View function did not return a response". I tried everything to get it works but no luck.
html code:
<form action="/NewCases/" method=post class="form-horizontal">
<h2>Add New Cases: </h2>
<div class="input-group">
<span class="input-group-addon">#</span>
<input type="text" id="casename" name="casename" class="form-control"
placeholder="Enter Case Name:" required>
</div>
<div class="input-group">
<span class="input-group-addon">#</span>
<input type="text" id="adminname" name="adminname" class="form-control"
placeholder="Enter Case Name:" value="{{ current_user.username }}">
</div>
<div class="input-group">
<span class="input-group-addon">#</span>
<input type="file" id="imagefile" name="imagefile" class="form-control"
placeholder="Enter Hard Disk File:" required>
</div>
<div class="input-group">
<span class="input-group-addon">#</span>
<input type="file" id="memimagefile" name="memimagefile" class="form-control"
placeholder="Enter Memory File:" required>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-success">Signup</button>
</div>
</div>
</form>
flask code
#app.route('/NewCases/', methods=['GET', 'POST'])
def NewCase():
try:
if request.method == 'GET':
return render_template('admin.html', DICT=DICT)
if request.method == 'POST':
idtest = str(uuid.uuid4())
idtestfilter = idtest.replace('-','')
adname= request.form['adminname']
casen = request.form['casename']
imagefile = request.files['imagefile']
memimagefile =request.files['memimagefile']
if imagefile > 0:
imagefilename = secure_filename(imagefile.filename)
file.save(os.path.join(UPLOAD_FOLDER , imagefilename))
return redirect(url_for('index'))
if memimagefile > 0:
imagefilename = secure_filename(memimagefile.filename)
file.save(os.path.join(UPLOAD_FOLDER , memimagefile))
return redirect(url_for('index'))
c, conn = connection()
c.execute("INSERT INTO cases(id,casename, adminname, imagepath, memimagepath) VALUES (%s, %s, %s, %s, %s)",
(thwart(idtestfilter),thwart(adname),thwart(casen),thwart(imagefilename),thwart(memfilename)))
conn.commit()
flash("case inserted!")
c.close()
conn.close()
flash('Cases successfully added')
return redirect(url_for('EditCase'))
except Exception as e:
error = e
Please help me out!
The first thing to point out is that your Python code is failing, but you are catching and ignoring all exceptions (well, almost all). The main reason that your Python code is failing is because a bad request is being received. You would know that if you did not catch and ignore all exceptions. At least print a message, and raise the exception again.
Anyway, you are uploading files so you need to set the encoding type for your HTML form to multipart/form-data, like this:
<form action="http://127.0.0.1:5000/" method=post enctype="multipart/form-data" class="form-horizontal">
That's the cause of the bad request.
I assume that you have imported all required modules and functions such as uuid, secure_filename etc., however, you are not quite saving the files properly. Use imagefile.save() and memimagefile.save(), not file.save().
Also, because both files can be uploaded at the same time, and because there is database code that should be run, you should not return after saving the files.
Finally, your code assumes that the form fields will always be present in the form. If one is missing your code will fail with a KeyError.
I am trying to make a python file into a python and html files. The code i have is basically from the python guestbook example but i want to have a html file serve the uses browser. the code i have works right now but when i add the javascript at the bottom i get an error This code is at ceemee11111.appspot.com
import cgi
import datetime
import urllib
import webapp2
from google.appengine.ext import db
from google.appengine.api import users
class Greeting(db.Model):
"""Models an individual Guestbook entry with an author, content, and date."""
author = db.StringProperty()
content = db.StringProperty(multiline=True)
content2 = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
def guestbook_key(guestbook_name=None):
"""Constructs a Datastore key for a Guestbook entity with guestbook_name."""
return db.Key.from_path('Guestbook', guestbook_name or 'default_guestbook')
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
guestbook_name=self.request.get('guestbook_name')
greetings = db.GqlQuery("SELECT * "
"FROM Greeting "
"WHERE ANCESTOR IS :1 "
"ORDER BY date DESC LIMIT 3",
guestbook_key(guestbook_name))
self.response.out.write("""
<form action="/sign?%s" method="post">
<div id="container" style="width:800px">
<div id="header" style="background-color:#FFA500;">
<h1 style="margin-bttom:0;">Main Title</h1></div>
<div id="Con0" style="background-color:#FFD700;
height:200px;width:200px;float:left;">
<b>Menu</b><br>
HTML<br>
CSS<br>
<p id="demo1"></p><br>
JavaScript</div>
<div id="content" style="background-color:#EEEEEE;height:200px;width:600px;float:left;">
Content goes here</div>
</div>
<button onclick="myFunction()">Try it</button>
</form>
</body>
</html>""")
self.response.out.write("""
<form action="/sign?%s" method="post">
<div id="dataImput"
<div><textarea name="content" rows="1" cols="10"></textarea></div>
<div><textarea name="content2" rows="1" cols="10"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</div>
</form>
<hr>
<form>Guestbook name: <input value="%s" name="guestbook_name">
<input type="submit" value="switch"></form>
</body>
</html>""" % (urllib.urlencode({'guestbook_name': guestbook_name}),
cgi.escape(guestbook_name)))
class Guestbook(webapp2.RequestHandler):
def post(self):
# We set the same parent key on the 'Greeting' to ensure each greeting is in
# the same entity group. Queries across the single entity group will be
# consistent. However, the write rate to a single entity group should
# be limited to ~1/second.
guestbook_name = self.request.get('guestbook_name')
greeting = Greeting(parent=guestbook_key(guestbook_name))
if users.get_current_user():
greeting.author = users.get_current_user().nickname()
greeting.content = self.request.get('content')
greeting.content2 = self.request.get('content2')
greeting.put()
self.redirect('/?' + urllib.urlencode({'guestbook_name': guestbook_name}))
app = webapp2.WSGIApplication([('/', MainPage),
('/sign', Guestbook)],
debug=True)
#<script>
#function myFunction()
#{
#document.getElementById("demo1").innerHTML="test";
#}
Thankyou for your time.
Dan
Given that you're clearly using GAE, what you are looking to do is outlined here.
First, move your html to separate files. We'll start with the html from the oddly freefloating self.response.out.write:
"""
<form action="/sign?%s" method="post">
<div id="dataImput"
<div><textarea name="content" rows="1" cols="10"></textarea></div>
<div><textarea name="content2" rows="1" cols="10"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</div>
</form>
<hr>
<form>Guestbook name: <input value="%s" name="guestbook_name">
<input type="submit" value="switch"></form>
</body>
</html>""" % (urllib.urlencode({'guestbook_name': guestbook_name}),
cgi.escape(guestbook_name))
This belongs in a separate file we'll call myhtml.html. Second, we then are going to go through and using the Django templating system instead of %s and Python string formatting. So first, we're going to replace the %s with template-friendly fields surrounded by {{ }}, giving us:
"""
<form action="/sign?{{ guestbook_name }}" method="post">
<div id="dataImput"
<div><textarea name="content" rows="1" cols="10"></textarea></div>
<div><textarea name="content2" rows="1" cols="10"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</div>
</form>
<hr>
<form>Guestbook name: <input value="{{ guestbook_name|escape }}" name="guestbook_name">
<input type="submit" value="switch"></form>
</body>
</html>"""
Note that we were able to use the escape template filter, which is what comes after the |, to escape the value we're getting from guestbook_name.
Finally, we load the html and pass it the arguments we need:
self.response.out.write(template.render('myhtml.html', {'guestbook_name': guestbook_name}))
I think your code will really benefit from separating the HTML from the Python code.
You can do that by writing an html template and use jinja2 (which comes with google appengine) to generate the html. There are instructions on how to do that here. The JavaScript would go in the HTML template, not in the Python code.