How to save a file, uploaded from a form to a local directory without using model? Also the form is being posted using ajax, so how do I render the file information from the html file?
Create an HTML form with
<form method="post" enctype="multipart/form-data" action="your_view_name">
<input name="myfile" type="file" />
</form>
Use AJAX to post the file. If you're using jQuery, see this link on how to post stuff
http://api.jquery.com/jquery.post/
In the view, use request.FILES to access the uploaded file. Use whatever Python APIs you have to save the file to the disk.
Related
I am using Django and have a template with the following input field:
<input type="file" name="file_upload">
When the form is submitted, I can access the submitted file like this:
request.FILES['file_upload']
Now that I have this file, I want to upload it to my S3 bucket from the Python backend. How can I do this? Thanks!
I have forms.Form in django. In this form there is a forms.FileField. This field is rendered in html as
<input id="id_upload-loaded_file" name="upload-loaded_file" type="file">
I need to add accepted files only with ".zip" extension so that form will be rendered as
<input id="id_upload-loaded_file" name="upload-loaded_file" type="file" accept=".zip">
How can I add accepted file extension attribute in django?
This is how I did it:
zip_file = forms.FileField(label='Select zip file', widget=forms.FileInput(attrs={'accept': '.zip'}))
I've installed Django-Photologue and I can upload files and create galleries in my Django admin site. I've been searching the documentation below for examples on how to create a photo upload form so my users can create a gallery on my site but can't find a simple example to get me started. I've also setup their example application but it wasn't very helpful in terms of how to upload and create Galleries by POSTing from Views/Templates.
Docs:
https://django-photologue.readthedocs.org/en/2.7/
https://code.google.com/p/django-photologue/
Can someone please provide a simple example of how I can create an upload form for submitting photos and creating a gallery for use with Django-Photologue ( not using just admin site)?
This is quite simple, Photologue has all the relevant logic inside its models.
For example to setup photo upload, you can use CBV:
urls.py
from django.views.generic import CreateView
from photologue.models import Photo
urlpatterns = patterns('',
url(r'^photologue/photo/add/$', CreateView.as_view(model=Photo),
name='add-photo'),
(r'^photologue/', include('photologue.urls')),
...
In your template, remember to set enctype attribute, to handle files.
templates/photologue/photo_form.html
<form action="" method="post" accept-charset="utf-8" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Submit">
</form>
That's basically all you need.. as you can see, we don't use any custom logic, everything is encapsulated inside Photo model and the CBV does the rest.
The same applies to Gallery, just replace the model with Gallery and you're good to go.
Obviously if you need some customization, you can do it as well, but that's outside the scope, since you didn't specify what use case you need to handle.
One thing missing from the answer above is you have to set the success_url in the CreateView.as_view. For example: CreateView.as_view(model=Photo, success_url='/')
Otherwise you'll receive a ImproperlyConfigured error.
I have 2 django models:
class Image(models.Model):
name = models.CharField(max_length=100)
photo = models.ImageField(upload_to='upload/', blank=True)
class Preview(models.Model):
photo = models.ImageField(upload_to='preview', blank=True)
Then I create ImageForm with ModelForm and render it in the html template.
I want to do image preview in the page.
I use https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin
<script src="/static/js/jquery.ui.widget.js"></script>
<script src="/static/js/jquery.iframe-transport.js"></script>
<script src="/static/js/jquery.fileupload.js"></script>
<script>
$(function () {
$('#id_photo').fileupload({
dataType: 'json',
url: '{% url preview %}',
always: function (e, data) {
$('#preview').css({'visibility': 'visible'});
$('#preview').prepend('<img src=/static/'+data.result.url+' />')
}
});
});
</script>
<form method="POST" action="edit/" enctype="multipart/form-data">
<div class="field">
{{ form.photo.errors }}
<label for="id_photo">Photo:</label>
<input type="file" name="photo" id="id_photo" >
</div>
<div id="preview">
</div>
<input type="submit" name="Change">
So with the help of javascipt I send image to server, resize it (in preview view - it process PreviewForm), save on disk and return the url which is inserted into img tag. It works.
After I press Submit button I can't receive image file in my view (edit which process ImageForm) : request.FILES is empty !!!
When I disable "uploading image with js" 'edit-view works fine: request.FILES contain image, and i can save it..
what causes disappearance request.FILES in second POST request ?
The first thing you need to learn is HTTP is stateless protocol. Every request a client does to a server is unique and independent from the previous one.
In your situation, you submit your form with the image that you want to upload and it makes the upload so that you can see the image in request.FILES and display a preview for it.
However, once you make the upload and show a new page, of course request.POST will be empty because you did not uploaded anything, the file is already in your server, waiting to be approved.
The proper solution will be, when preparing the preview, create some hidden input fields which will help you to identify what photo you want to approve (unique ids are very good in this case, also don't expose file paths directly to your client unless you are the only one who's using the app).
Then in the second request, retrieve those hidden fields, locate the image and do what you are going to do; in your case, approve and make it public somehow.
I looked at this question:
Uploading multiple files with Django
but it did not seem to help as I have issues regarding it:
I don't want to deal with flash sessions using SWF Upload and Uploadify because I need to do uploads that only authenticated users can do.
newforms are for older versions of django, I am using 1.3
Using Django, how can I have this HTML form structure:
<form enctype="multipart/form-data" action="." method="post">
<label for="id_image_1">Image 1</label>
<input type="file" name="image[]" id="id_image_1" />
<label for="id_image_2">Image 2</label>
<input type="file" name="image[]" id="id_image_2" />
</form>
and handle it using a view?
If you have a fixed number of filefields, you could simply define a form with enough filefields, or add filefields programatically in a form's constructor. See the Django docs on File Uploads.
If you want some sort of dynamic functionality (a la gmail's "add another file"), then you could define a formset using a form with a single filefield. Display a single form initially and when you want to add another, use a little javascript to produce the new form and update the formset's management form. There are a number of snippets floating around to help you do this, though they may need some tweaking. See the Django docs on File Uploads and Formsets.
Another option may be to use a custom widget and field, though I have not reviewed or tried this.
On the off-chance you aren't aware, the name="image[]" scheme is PHP specific and has no special meaning in other languages, unless you reimplement it.
newforms is what the current forms were called before 1.0. Furthermore, if you got your form validated, http://docs.djangoproject.com/en/dev/topics/http/file-uploads/, you'll have your files as a list (tuple, probably, but sequence anyway) in request.FILES['image'], so just do:
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
for f in request.FILES['image']:
handle_uploaded_file(f)
You'll have to write handle_uploaded_file yourself, the URL explains how