django - how to post array of images to views - python

i am stuck on this issue since yesterday. i have a form where user can select more image files and submit. now i am not able to catch those POSTED image files in my views.py.
my html:
<input type="file" name="images[]" />
<input type="file" name="images[]" />
and in my views.py i did this:
images = request.POST.getlist('images[]')
but once i print images, i am getting [], empty array. what am i doing wrong? i want to get all selected image files and save them into db in my view.
EDIT:
this is my html:
<form action="/save/" method="post" enctype="multipart/form-data">
<input type="file" name="images[]" />
<input type="file" name="images[]" />
<input type="submit" value="send" />
</form>
this is my views.py
fotos = request.POST.getlist('images[]')
for i in range(len(fotos)):
print fotos[i]
here it is printing [], and not the names of each images. why is this array empty?
thanks for help.

When Django handles a file upload, it's a little different than a regular POST field. The data is place in request.FILES and needs to be accessed there. The documentation about handling file uploads is a great starting point.

Related

multiple inputs of the same name in an html form

I have some html code that contains a form. When submitted it sends a post request to a server. The form has various inputs, each with a name and a value, however there are some inputs with the same name.
Here is an example of what I mean:
<form action="http://example.com" method="post">
<input name="name" value="val">
<input name="name" value="val">
<input type="submit">
</form>
First, I am confused as to how there can be two values of the same name. Please note that I have tried removing one of the instances of <input name="name" value="val"> however this returns an error so it seems that both instances are needed.
Second, I am trying to convert this to a python request using the request library.
I have the following request:
requests.get(url = URL, params = PARAMS).json()
Where PARAMS is a dictionary of the various inputs. For example:
PARAMS = {'name':"val"}
However, being a dictionary, I can't have multiple instances of the same value. How do I make this work? Thanks
If there are duplicated names then the values will be in an array with the name. The demo below sends to a live test server and the response is directed to an <iframe>
<form action="https://httpbin.org/post" method="post" target="response">
<input name="name" value="val">
<input name="name" value="val">
<input type="submit">
</form>
<iframe name='response'></iframe>
What you are looking for is to use input arrays. With them, you can have many inputs sharing the same name, and in the server side, the data will be treated as an array. So the HTML would be:
<form action="http://example.com" method="post">
<input name="name[]" value="val1">
<input name="name[]" value="val2">
<input type="submit">
</form>

Uploading Images Django Python

html:
<label for="image">Image</label>
Select a file: <input type="file" name="img">
Python:
image = (request.FILES.get("img"))
When I print image it prints none. If I just use {{form}} in between the <form> </form> tags it does send the image across to the view. However, for some specific reason I do not want to use the {{form}} method.
Any ideas how I can approach this problem? Thanks in advance!
Make sure your <form> has enctype="multipart/form-data", so it should look something like:
<form method="post" action="{URL}" enctype="multipart/form-data">
<input ...>
</form>

How to get form POST input in Tornado?

I amd new to Tornado framework and trying to make a simple form to upload images:
<form method="post" action="/uploads/{{uid}}/" enctype="multipart/form-data" >
<input type="file" name="file1" /> <br />
Image info: <input type="text" name="alt" /> <br />
<input class="button" type="submit" value="Upload" class="button" />
</form>
I can successfully receive the Posted file using:
if 'file1' in self.request.files:
if self.request.files['imgfile'][0]:
file1 = self.request.files['imgfile'][0]
However I'm unable to receive the alt input. I tried alt = self.request.alt but I get this error
AttributeError: 'HTTPServerRequest' object has no attribute 'alt'
and when I use alt = self.request.files['alt'], I get:
KeyError: 'alt'
I ran out of ideas so appreciate your help.
UPDATE:
I found that this works:
alt = self.get_argument('alt')
But still open for better solutions.
Try code below
self.get_body_argument("alt", default=None, strip=False)

How to pass variables to a form before it is processed

I have the following template form, containing several variables.
<form action="https://me.s3.amazonaws.com/" method="post" enctype='multipart/form-data' class="upload-form">
<input type="hidden" name="key" value="videos/{{filename}}">
<input type="hidden" name="AWSAccessKeyId" value="{{access_key}}">
<input type="hidden" name="acl" value="public-read">
<input type="hidden" name="policy" value="{{policy}}">
<input type="hidden" name="signature" value="{{signature}}">
<input type="hidden" name="Content-Type" value="{{content_type}}">
<input name="file" type="file">
<input type="submit" value="Upload" name="upload">
</form>
However, as soon as the submit button is hit, the form is sent to amazon, and I'm not able to pass it variables. This is what I've been trying to do, unsuccessfully --
if 'upload' in request.POST:
policy = base64.b64encode(...)
signature = base64.b64encode(
hmac.new('secret_key', policy, sha).digest())
file = request.POST['files']
filename=file.name
content_type=mimetypes.guess_type(filename)[0]
What do I need to do to pass the variables to the form after the POST request but BEFORE amazon processes the form? Thank you.
You should change your form's action to your django view and in your view you can re-post to https://me.s3.amazonaws.com/:
In your template
<form action="http://mywebsite/upload" method="post" ...
In your view.py:
def upload(request):
# Your treatment here.
# Post the data to amazon S3.
urllib2.urlopen("https://me.s3.amazonaws.com/", your_data)
...
You could change the form to POST to one of your own views, then do your post-processing in your view, and then within your view code, issue a POST to Amazon with the correct values using, say, urllib2 or similar.

How to upload multiple files to BlobStore?

I'm trying to upload multiple files in a form to the BlobStore.
Form:
<form action="{{upload_url}}" method="POST" enctype="multipart/form-data">
<label>Key Name</label><input type="text" name="key_name" size="50"><br/>
<label>name</label><input type="text" name="name" size="50"><br/>
<label>image</label><input type="file" name="image" size="50"><br/>
<label>thumb</label><input type="file" name="thumb" size="50"><br/>
<input type="submit" name="submit" value="Submit">
</form>
I'm then trying to fetch the BlobInfo objects for each of those files uploaded:
def post(self):
image_upload_files = self.get_uploads('image')
thumb_upload_files = self.get_uploads('thumb')
image_blob_info = image_upload_files[0]
thumb_blob_info = thumb_upload_files[0]
I'm seeing some weird behavior. Both files are making it into the BlobStore, but I cannot figure out how to get the Keys so that I can store those on another Entity. The code above manages to get the key for image_blob_info, but not thumb_blob_info. I don't understand how to use get_uploads. I want to pass multiple files through the form and then fetch them by name so I can store them in the appropriate BlobReferenceProperties on another Entity.
Each file needs its own unique upload url, so my guess is something wacky is happening when all three files are posted to the same url.
The best solution for supporting multiple file uploads is described in Nick Johnson's blog post:
http://blog.notdot.net/2010/04/Implementing-a-dropbox-service-with-the-Blobstore-API-part-3-Multiple-upload-support
You could post the files to the same name, followed by [], which will post an array:
<form action="{{upload_url}}" method="POST" enctype="multipart/form-data">
<label>Key Name</label><input type="text" name="key_name" size="50"><br/>
<label>name</label><input type="text" name="files[]" size="50"><br/>
<label>image</label><input type="file" name="files[]" size="50"><br/>
<label>thumb</label><input type="file" name="thumb" size="50"><br/>
<input type="submit" name="submit" value="Submit">
</form>
Then in your form handler, you can something like this (depending on your web framework):
for uploaded_file in request.FILES.getlist('files'):
#do something with uploaded_file
Using the latest version of plupload, I was able to get the UploadQueue to work with GAE with this bit of code. Note, it is CoffeeScript, but should be easy to convert back to JavaScript if you really need to. It assumes you get a bit of json back from your server as {url:"gae generated url"}
$("#fileUploader").pluploadQueue
runtimes : 'html5,html4'
use_query_string : false
max_file_size : '3mb'
multipart: true
unique_names : true
multiple_queues : true
filters : [{title : "Image files", extensions : "jpg,gif,png"}]
preinit:
UploadFile: (up, file) ->
$.ajax
url: '/api/upload/url'
async: false
success: (data) ->
up.settings.url = data.url

Categories