upload image in django form - python

am uploading image , but its not working the function is :
in views
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/user_profileform/')
else:
form = UploadFileForm()
return render_to_response('user_profile.html', {'form': form })
def handle_uploaded_file(f):
with open('ranjeet.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
form is:
<form action="" method="POST" enctype="multipart/form-data" name="uform" id="userform">{% csrf_token %}
{{form}}
<input type="submit" value="submit" name="usubmit">
</form>
in settings :
MEDIA_ROOT = '/media/images/'
MEDIA_URL = '/media/'
i dont know where the file has been saved.

I think the issue is while you are trying to open a destination. There you have provided "ranjeet.txt" which is a file. There you should provide the path of your harddisk/folder path, where you want to save your uploaded file.
Please try using this code:
destination = open(settings.MEDIA_ROOT, 'wb+')
for chunk in f.chunks(): //f is the file info passed to handle_file_upload(f)
destination.write(chunk)
destination.close()
Another issue I found in your code. in form action neither i found any url nor "."

Related

How to manage uploaded file in django

i want to manage(move and rename)files that user upload :
my upload form(html):
<form action="../valid_upload/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input type="submit" name="send" value="send" />
</form>
my form(django part):
class UploadImageForm(forms.Form):
image = forms.FileField()
name = forms.CharField(max_length=100)
about = forms.CharField(widget=forms.Textarea)
taq1 = forms.CharField(max_length=100)
taq2 = forms.CharField(max_length=100)
taq3 = forms.CharField(max_length=100)
url.py(just a one line):
url(r'valid_upload/', views.valid_upload, name='valid_upload'),
and view.py(just a part of that):
if 'username' in request.session:
if request.method == 'POST':
if 'image' in request.FILES:
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
# Here goes the documentation code
return HttpResponse(request.FILES['image'].content_type)
//here i want to rename and move uploaded files
else:
return redirect('/upload_image')
else:
return redirect('/login/')
i want to know how to rename uploaded file and move them on my directories.if you can help me :)
You can pass the request data to your form, and let the form manage your needs. Here is an example:
if 'username' in request.session:
if request.method == 'POST':
if 'image' in request.FILES:
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
# Here goes the documentation code
return HttpResponse(request.FILES['image'].content_type)
//here i want to rename and move uploaded files
else:
return redirect('/upload_image')
else:
return redirect('/login/')
You can use a django model too.
Here is the documentation:
https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/

Save Multiple Files from Django Forms to Model

Looking to upload 2 files into a Django Form using HTML5 (since it supports multi-file upload). The problem I'm facing is it's targets the 1st one for uploading. It knows there are 2 files, because when it saves, it saves twice (as per the for loop below). I thought to use the dictionary to loop over the names, but I receive an error that says this keyword can't be an expression. Maybe this is something simple, but if you need more, I can provide. Just a note, I did not use the forms.py for the file upload, but instead just the regular HTML <input tag. Thanks.
#page.html
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form_a.as_p }}
<input type="file" name="img" multiple>
<input type="submit" value="Submit" />
</form>
#models.py
def contact(request):
if request.method == 'POST':
form_a = RequestForm(request.POST, request.FILES)
if form_a.is_valid():
#assign form data to variables
saved_first_name = form_a.cleaned_data['First_Name']
saved_last_name = form_a.cleaned_data['Last_Name']
saved_department = form_a.cleaned_data['Department']
saved_attachments = request.FILES.getlist('img')
#create a dictionary representing the two Attachment Fields
tel = {'keyword1': 'Attachment_2', 'keyword1': 'Attachment_1'}
for a_file in saved_attachments:
#for every attachment that was uploaded, add each one to an Attachment Field
instance = Model(
Attachment_1=a_file,
Attachment_2=a_file
)
instance.save()
all_together_now = Model(First_Name=saved_first_name, Last_Name=saved_last_name,
Department=saved_department, Attachment_1=???, Attachment_2=???)
#save the entire form
all_together_now.save()
else:
#just return an empty form
form_a = RequestForm()
return render(request, 'vendor_db/contact.html', {'form_a': form_a})
Here is a way that worked for me. I loop each occurrence of an InMemoryUploadedFile in request.FILES and re-assign it back onto request.FILES, then save each one by one.
forms.py
class PhotosForm(forms.ModelForm):
file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta:
model = Photos
fields = ['file']
views.py
def photos(request):
photos = Photos.objects.all()
if request.method == 'GET':
form = PhotosForm(None)
elif request.method == 'POST':
for _file in request.FILES.getlist('file'):
request.FILES['file'] = _file
form = PhotosForm(request.POST, request.FILES)
if form.is_valid():
_new = form.save(commit=False)
_new.save()
form.save_m2m()
context = {'form': form, 'photos': photos}
return render(request, 'app/photos.html', context)

uploading image in django

I'm writing a simple file uploader for a website. The user sees a form:
<form action="/user_profileform/" method="POST" enctype="multipart/form-data" name="uform" id="userform">{% csrf_token %}
{{form}}
<input type="submit" value="submit" name="usubmit">
</form>
and upon submit, I redirect to this function:
#csrf_exempt
def upload_file(request):
if request.method == 'POST':
print "arun";
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/user_profileform/')
else:
print "ranjeet"
form = UploadFileForm()
return render_to_response('user_profile.html', {'form': form })
def handle_uploaded_file(f):
destination = open(settings.MEDIA_ROOT, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
When I try this functionality out, I'll always get an exception:
IOError at /user_profileform/
[Errno 21] Is a directory: '/home/ghrix/ghrixbidding/media/images/'
You're trying to open settings.MEDIA_ROOT which is directory.
Because settings.MEDIA_ROOT is directory. You need to provide filename for handle.
Is better to use Model with FileField, because it generates unique file name in media automatically. It is described in https://docs.djangoproject.com/en/1.5/topics/http/file-uploads/

Upload file with FileField and nginx just throw errors?

I'm new to Django, I'm learning how to handle uploading file with django, I did the same things with the document, but my nginx just throw out errors,
here is my views.py:
#csrf_exempt
def upload_view(request):
if request.method == 'POST':
form = UploadItemForm(request.POST, request.FILES)
if form.is_valid():
return HttpResponse('successfully uploaded')
else:
return HttpResponse('upload failed')
else:
if request.user.is_authenticated():
form = UploadItemForm()
return render(request,
'design/upload.html',
{'form': form,
'username': request.user.username})
else:
return HttpResponse("you have to login")
model.py
class Item(models.Model):
name = models.CharField(max_length = 100)
description = models.TextField(max_length = 1000)
uploadfile = models.FileField()
class UploadItemForm(ModelForm):
class Meta:
model = Item
my template:
<form enctype="multipart/form-data" method="post" action="/design/">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="upload" />
</form>
if I upload some text-based file (size is very small), everything is OK, when upload other formats, or large csv file, the code failed on
form = UploadItemForm(request.POST, request.FILES)
nginx says
Sorry, the page you are looking for is currently unavailable. Please
try again later.
I use nginx+uwsgi+django, so is it related to the uwsgi and nginx setup?
Ah, I solved it. For some unknown reason. It seems that, when the request size is beyond some threshold, nginx will put data on client_body_temp/ directory, for some reason(I don't know it), this directory in my setup is read-only by root???? change the permission, then everything goes fine
For additional info:
client_max_body_size 4M; //4mb
default_type text/plain; //file format
Here are the list of functions: http://nginx.org/en/docs/http/ngx_http_core_module.html
Read also this forum: http://forum.slicehost.com/index.php?p=/discussion/1714/nginx-413-when-uploading-file-1mb-or-larger/p1

Form from Model with File Upload

I'm trying to mimic the admin interface for the Photologue app on the front end. To achieve this, I have thus far created a bit of code in the view:
def galleryuploader(request):
GalleryFormSet = modelformset_factory(GalleryUpload)
if request.method == 'POST':
formset = GalleryFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
# do something. ... do what?
else:
formset = GalleryFormSet()
return render_to_response("cms_helper/gallery_upload.html", {
"formset": formset,
})
and a template:
<form method="post" action="">
{{ formset }}
<input type="submit" />
</form>
I'm using django's "form from models" method for generating this front-end form.
The problem: when I try to upload a file (because I am uploading photos to a photo gallery), and hit submit, it returns with a form error telling me that a required field was missing (the file).
I think I am not checking the request for any files, but even if I were to, I'm not quite sure how to. Here's some documentation about file uploads, but I haven't been able to decipher it yet.
If you have any suggestions about how to make this upload form work, I'd be veryyy happy to hear them. Thanks in advance!
Add the enctype="multipart/form-data" attribute to your form tag. Also you'll need to actually do something with the uploaded files. Here's the example from the django docs:
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
# you'll need to loop through the uploaded files here.
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
def handle_uploaded_file(f):
destination = open('some/file/name.txt', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
(See the comment about halfway through)

Categories

Resources