问题
I'm trying to use sorl-thumnail to resize the image in the views then saving it and getting IOError while calling get_thumnail(). Also I need to know how to save the resized image. Sorry if you consider this silly..I'm new to Django.
Models.py:
from django.db import models
from django.forms import ModelForm
from sorl.thumbnail import ImageField
class BasicModel(models.Model):
name = models.CharField(max_length=200)
dob = models.DateField()
photo = ImageField(upload_to='sample')
class BasicModelForm(ModelForm):
class Meta:
model = BasicModel
Views.py:
def BasicView(request):
if request.method == 'POST':
form = BasicModelForm(request.POST, request.FILES)
if form.is_valid():
im = get_thumbnail(request.FILES['photo'], '100x100', crop='center', quality=99)
data = form.save()
return preview(request, data.id, im)
else:
form = BasicModelForm()
return render_to_response("unnamed.html", {'form': form}, context_instance=RequestContext(request))
def preview(request, id, im):
obj = get_object_or_404(BasicModel, pk=id)
return render_to_response("preview.html", {'obj': obj, 'im': im})
preview.html:
{{ obj.name }}
{{ obj.dob }}
{% load thumbnail %}
{% thumbnail im "100x100" as image %}
<img src="{{ image.url }}" width="{{ image.width }}" height="{{ image.height }}">
{% endthumbnail %}
Settings.py:
MEDIA_ROOT = '/home/nirmal/try/files/'
MEDIA_URL = 'http://localhost:8000/files/'
Errors:
Exception Type: IOError
Exception Value:
[Errno 2] No such file or directory: u'/home/nirmal/try/files/wp.jpg'
Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/files/storage.py in _open, line 159
Traceback: im = get_thumbnail(request.FILES['photo'], '100x100', crop='center', quality=99)
Could anyone help me on this? Thanks!
回答1:
You can't use request.FILES['photo'] here because uploaded file can be in memory or somewhere else. Save this file to filesystem first, then use get_thumbnail. For example, you can call it on your objects after it's returned by form.save().
回答2:
If you want to access the uploaded file directly then first you will have to get the path of temp memory where it is uploaded.
import os
import tempfile
def _file_path(uploaded_file):
''' Converts InMemoryUploadedFile to on-disk file so it will have path. '''
try:
return uploaded_file.temporary_file_path()
except AttributeError:
fileno, path = tempfile.mkstemp()
temp_file = os.fdopen(fileno,'w+b')
for chunk in uploaded_file.chunks():
temp_file.write(chunk)
temp_file.close()
return path
Then you can access the uploaded file at path:
path = _file_path(request.FILES['photo'])
来源:https://stackoverflow.com/questions/9549059/sorl-thumnail-resizing-and-saving