sorl-thumbnail调整大小和保存

时间:2012-03-03 19:16:27

标签: python django sorl-thumbnail

我正在尝试使用sorl-thumnail来调整视图中的图像大小,然后在调用get_thumnail()时保存它并获取IOError。此外,我需要知道如何保存调整大小的图像。对不起,如果你认为这是愚蠢的......我是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/'

错误:

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) 

有人可以帮我这个吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

你不能在这里使用request.FILES ['photo']因为上传的文件可以在内存或其他地方。首先将此文件保存到文件系统,然后使用get_thumbnail。例如,您可以在form.save()返回对象后调用它。

答案 1 :(得分:0)

如果要直接访问上传的文件,首先必须获取上传文件的路径。

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

然后您可以通过路径访问上传的文件:

path = _file_path(request.FILES['photo'])