2015-05-25 192 views
3

我想调整图像大小(枕头)上传之前,我写下面的代码,但不工作! 并得到错误:Django:上传前调整图像大小

AttributeError at /myapp/list/

_committed

Request Method: POST

Request URL: http://127.0.0.1:8000/myapp/list/ Django Version: 1.8 Exception Type: AttributeError Exception Value:

_committed

Exception Location:

/usr/local/lib/python3.4/dist-packages/Pillow-2.8.1-py3.4-linux-x86_64.egg/PIL/Image.py

in getattr, line 622 Python Executable: /usr/bin/python3.4 Python Version: 3.4.0

views.py

def list(request): 
# Handle file upload 
if request.method == 'POST': 
    form = DocumentForm(request.POST, request.FILES) 
    if form.is_valid(): 
     imga = request.FILES['docfile'] 
     size = (600, 400) 
     im = Image.open(imga) 
     imga = im.resize(size) 
     request.FILES['docfile'] = imga 
     newdoc = Document(docfile = request.FILES['docfile'], namefile=request.POST['namefile']) 
     newdoc.save() 

     # Redirect to the document list after POST 
     return HttpResponseRedirect(reverse('myproject.myapp.views.list')) 
else: 
    form = DocumentForm() # A empty, unbound form 

# Load documents for the list page 
documents = Document.objects.all() 

# Render list page with the documents and the form 
return render_to_response(
    'myapp/list.html', 
    {'documents': documents, 'form': form}, 
    context_instance=RequestContext(request) 
) 
+2

与您的问题无关,而是问题标题:您知道您正在服务器端重新调整图像大小,因此技术上*在上传之后(而不是之前)。 –

回答

0

对于图片大小,您可以利用djanof容易缩略图库。

下面是示例代码,我在我的项目

options = {'size': (200, 200), 'crop': True} 
thumb_url =get_thumbnailer(image path).get_thumbnail(options).url 

已用于参考https://github.com/SmileyChris/easy-thumbnails

19
from PIL import Image 
from io import BytesIO 
from django.core.files.base import ContentFile 
from resizeimage import resizeimage 

class SomeModel(models.Model): 
    image = models.ImageField(upload_to=your_get_file_path_callback) 

    def save(self, *args, **kwargs): 
     pil_image_obj = Image.open(self.image) 
     new_image = resizeimage.resize_width(pil_image_obj, 100) 

     new_image_io = BytesIO() 
     new_image.save(new_image_io, format='JPEG') 

     temp_name = self.image.name 
     self.image.delete(save=False) 

     self.image.save(
      temp_name, 
      content=ContentFile(new_image_io.getvalue()), 
      save=False 
     ) 

     super(SomeModel, self).save(*args, **kwargs) 

附:调整大小我已经使用了'python-image-resize'https://github.com/charlesthk/python-resize-image

+0

当你刚分配'self.image = new_image_io'时会发生什么 – Clayton

0

有一些有用的答案,但你可能想了解当前的代码是怎么回事。

代码中引发了该异常,因为这行:

request.FILES['docfile'] = imga 

有什么不好呢?你正在影响一个枕头对象到一个django ImageField元素。这些是两种不同的类型,当你打电话给Document构造函数时,它可能期望找到一个包含_committed属性的文件表单域。