how to save images from a multiple input in django - django

That is in templates, I have the following code. the file input has a multiple attribute in the end so that I can select multiple images.
<form method='POST' action="{% url 'method' %}" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="img" multiple />
<input type="submit" />
</form>
<br />
Then I am having trouble to save the image to my model. I tried to print request.FILES, and I got this
<MultiValueDict: {'img': [<InMemoryUploadedFile: 1.jpg (image/jpeg)>,
<InMemoryUploadedFile: 2.jpg (image/jpeg)>, <InMemoryUploadedFile: 3.jpg
(image/jpeg)>]}>
There are 3 items in 'img', I also used request.FILES.getlist('img'), doesn't really work out. How am I suppose to access the content in the 'img' like accessing several individual request.FILES. Thanks!!!

Well, I cannot believe I solved the problem 10mins after I posted it. The key is still
request.FILES.getlist('img'), but make sure you don't use chunks() later, so if you want save the image, save it directly like
for image in request.FILES.getlist('img'):
xxxx.image = image
xxx.save()
That's it. don't use any chunks() methods.

Related

django parameter via get not working while forming direct url

Base URL:
path('api/product/',
include(('store.urls', 'store'),
namespace='api-product')),
Store URL:
path('invoice-pdf-get/',
invoice.InvoiceToPdf.as_view(),
name='invoice-pdf-get'),
HTML:
<html>
<body>
<form method="get" action="{% url 'api-product:invoice-pdf-get' %}?R={{ invoice.invoice_unique_number }}">
<input type="submit" value="Generate PDF">
</form>
</body>
</html>
When I hit the button, I get the url in browser as:
http://localhost:8000/api/product/invoice-pdf-get/?
Where as expecting:
http://localhost:8000/api/product/invoice-pdf-get/?invoice_number=SOMEKEY
Though if I submit a hidden type input via form, I get the expected result but I was reading: Daniel Roseman SO answer. to pass parameter via GET.
Though inspect shows the URL (see image) but why am I not getting expected result?
When a form is submitted via GET, the values in the form are sent as the querystring. This overrides any querystring in the action URL. See this SO answer for example.
You should put your value as a hidden input in the form itself.
<form method="get" action="{% url 'api-product:invoice-pdf-get' %}">
<input type="hidden" name="R" value="{{ invoice.invoice_unique_number }}">
<input type="submit" value="Generate PDF">
</form>

Django 1.8 handwritten form no POST data

I've become very frustrated by a problem I'm having. I have a large form that's hand-written (not using Django's forms), and am simply trying to access the data from the inputs in the views (in that case, some inputs were posting, others weren't).
Leaving the specifics of that form aside for now since there are too many things at play, in my troubleshooting process I wrote the simplest form I could think of, and am now getting no POST data besides the csrf_token.
I have no idea why this would be, since something similar (and much more complex) works fine on several other django projects I'm running. For this example, I tried with action="" as well to no avail. Is there something incredibly obvious I'm missing?
Here's the html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="POST" id="theForm" action="/simpleForm/">{% csrf_token %}
<input type="text" id="theText" value="Where am I?" />
<input type="hidden" id="hiddenInput" value="I don't exist" />
<input type="submit" />
</form>
</body>
</html>
Here is a simple view checking for data:
from django.shortcuts import render
def simpleForm(request):
if (request.method == 'POST'):
print('In post')
print(request.POST)
for i in request.POST.keys():
print('key: {0} value: {1}'.format(i, request.POST[i]))
return render(request, 'simpleForm.html')
else:
return render(request, 'simpleForm.html')
You're missing the 'name' attribute of the tags in your HTML form. Without those, Django will not add them to request.POST
<form method="POST" id="theForm" action="/simpleForm/">{% csrf_token %}
<input type="text" id="theText" name="mytext" value="Where am I?" />
<input type="hidden" id="hiddenInput" name="myhidden" value="I don't exist" />
<input type="submit" />

Django Form Submission Error

I have this recurring problem with form submission in Django, and the frustrating part is that I'm not sure how to interpret what's happening. Essentially I have different pages with form submissions on them. Some of them work as following
localhost/page/formpage--> localhost/page/receivingpage
which is what I expect. Othertimes, it goes to a page like this
localhost/page/formpage--> localhost/page/formpage/recevingpage
and the screen shows a blank form page, which is not what I expect. I'm not sure how to interpret this, and I'm not sure where to look for errors in my code. I think I don't fully understand what's going on when I submit a form, how does it generate a URL after I press 'submit'?
Edit: here is my html form:
<!DOCTYPE HTML>
<html>
<div>
<p>Entry Form</p>
<form action= "user" method="post" >
{% csrf_token %}
<p><label for="id_username">Username:</label>
<input id="id_username" type="text" name="username"" /></p>
<p><label for="id_password">Password</label>
<input type="password" name="password" id="id_password" /></p>
<input type="submit" value="Submit" />
</form>
</div>
</html>
I suspect it isn't the form, I have it on another application and it works... the trouble is I don't know if it's the view, the template, or w/e, so I'll update the post with info as people request it.
I'd recommend putting in an action using the url template tag. With that, you will know for certain where the form is going to end up:
<form action="{% url 'user-url-name' %}" method="post">
The url tag will be an absolute url. Without this, you're going to end up at a relative url depending on where in your application the user submits the form, which can be quite confusing during development and not entirely correct.
Using {% url %} tag is the proper way to do. Your problem can also be solved by adding a forward slash / to the action attribute like this:
<form action="/user" method="post" >
Hope this helps!

Django Upload From Template

I am looking into uploading a file from the html template. I've seen a fair amount of documentation including FileFields, ImageFields etc. However, ideally I do not want to rewrite my code.
Currently, I have a simple form on my template and I would like to have an upload function there, where, an image will be uploaded and stored into my applications media folder and if possible added to a database.
I do know that I've probably taken a long and complex route but if anyone can help it'll be great!
html.py:
<div class="row"> <div class="span1 offset5"> </bR>
<form class="form-horizontal" method="get" action="/add/submit" value="add">
<fieldset> <div class="input">
<div class="inline-inputs">
<label>Ride Name:</label><input type="text" name="name">
<label>Type:</label><input type="text" name="type">
<label>Theme:</label><input type="text" name="theme">
<label>Description:</label><textarea rows="5" name ="description"></textarea>
<label>Author:</label><input type="text" name="author">
<label>Date Released:</label>
<div id="datetimepicker" class="input-append date">
<input type="text" name="date"></input>
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
</span>
</div>
<label>Thread:</label><input type="text" name="thread">
<label>Video</label><textarea rows="2" name ="video"></textarea>
<br><br>
<input class="btn btn-primary" type="submit" value="Add" />
</div> </div>
</fieldset>
</form>
</div> </div>
Currently my Views.py just takes the entered data and inserts it into a database. I want to add the ability for a file to be uploaded:
def Ride_Add_Submit(request):
name = request.GET['name']
type = request.GET['type']
theme = request.GET['theme']
description = request.GET['description']
author = request.GET['author']
releasedate=request.GET['date']
video=request.GET['video']
thread=request.GET['thread']
entry = RollerCoaster(name=name, type=type, theme=theme, description=description, releasedate=releasedate, author=author, video=video, thread=thread)
entry.save()
return TemplateResponse(request, 'Ride_Add.html')
I don't understand why you keep talking about the template here, the template has nothing whatsoever to do with anything. The handling of the upload, like all logic, is done in the view.
The file upload overview still has all the information you need. You can ignore the parts about the Django form and checking if it's valid, and simply pass the file object to your upload handling function, which that page also explains.
However you will need to change your template so that the form element uses POST instead of GET (which is almost certainly a good idea anyway), and use enctype="multipart/form-data" as also described on that page.
Finally, I really would advise you to rewrite your code to use ModelForms. Not only would it make your code much simpler, it would also do things like validate the entry to make sure all the required fields are present and are of the right types, and so on - as well as output valid HTML (for instance, you're missing for attributes in your label tags).

Uploading images in Django not working

I am trying to use Django to upload images to a directory on disk. For some reason I'm can't get this to work properly. I get redirected to the submit-success.html page with no errors, however the file doesn't get uploaded. I've provided some code below. Any help would be greatly appreciated. Thanks in advance.
NB:
I'm working on the development server,
I'm using django 1.3,
I'm using sqlite3
This is my form in upload.html
<form enctype="multipart/form-data" action="{% url upload_success %}" method="post">
{% csrf_token %}
<table>{{ form }} </table>
<input type="submit" value="Submit image">
</form>
Here is a link to some code I have written:
https://gist.github.com/1468190
Your handle_uploaded_image method seems faulty. For example, with these lines:
photo_dir = '%s/uploaded_photos/Not_Published/%Y/%m/%d' % settings.MEDIA_ROOT
photo_destination = open(photo_dir, 'wb+')
You're attempting to open a file in "YYYY/MM" with the name of "DD". If you already have "DD" as a directory, this will not work, and if you don't your image is going to be saved as "DD" not as "image.jpg" or whatever. So your image may very well be getting saved, but you're not recognizing it.