Django中的文件上传/处理

时间:2011-11-16 04:36:52

标签: python django django-models django-forms

我已经连续工作了3天,而且我已经结束了。我需要有人一步一步地解释这个过程中究竟发生了什么,以及每一步的实际数据是什么(或看起来像什么)。

我有一个带有ImageField()的模型。我有一个基于该模型的表单。我将表单传递给模板,该模板将完成的表单数据传递给视图。然后我将request.FILES数据绑定到模型/表单的实例,并保存它。

我想要做的是将此上传的文件用作我的用户的个人资料图片,并且我想在将其保存到模型中之前调整其大小。

在我验证了数据之后,我将request.FILES ['file']数据传递给函数,并且在此函数内部PIL打开数据。它打开很好,每次我都没有问题,PIL直接从InMemory文件中查看这些数据。但是,我无法让PIL将这些编辑过的数据输出到Django在其ImageField()中寻找的内容。我基本上想要获取这些上传的数据,调整它的大小,重命名它,然后通过ImageField()保存它,让Django从那里处理它。

观点:

if request.method == "POST":
    user_form = EditUserProfile(request.POST, instance=User.objects.get(id=request.user.id))
    siteprofile_form = EditSiteProfile(request.POST, request.FILES, instance=SiteProfile.objects.get(user=request.user))
    if user_form.is_valid() and siteprofile_form.is_valid():
        user_form.save()
        temp_siteprofile = siteprofile_form.save(commit=False)
        temp_siteprofile.profile_image = process_image_string(request.FILES['profile_image'], (100, 100))
        temp_siteprofile.save()
        return user_profile(request, request.user.username)

功能:

def process_image_string(f, size):
    f_image = Image.open(f)
    f_image = f_image.resize(size)
    output = StringIO()
    f_image.save(output, "JPEG")
    return output

请记住,功能在过去3天内可能已经改变了100次,这是(在我看来)我最接近的成功。

1 个答案:

答案 0 :(得分:1)

考虑尝试django-stdimage。这是ImageField的扩展,会为您调整图片大小,这是一个示例代码段:

class MyClass(models.Model):
    image1 = StdImageField(upload_to='path/to/img') # works as ImageField
    image2 = StdImageField(upload_to='path/to/img', blank=True) # can be deleted through admin
    image3 = StdImageField(upload_to='path/to/img', size=(640, 480)) # resizes image to maximum size to fit a 640x480 area
    image4 = StdImageField(upload_to='path/to/img', size=(640, 480, True)) # resizes image to 640x480 croping if necessary

    image_all = StdImageField(upload_to='path/to/img', blank=True, size=(640, 480), thumbnail_size=(100, 100, True)) # all previous features in one declaration

有了这个,您可以直接保存ModelForm EditUserProfile,而不需要自己执行任何图像处理。缺点是该库专门使用PIL。

Google代码:http://code.google.com/p/django-stdimage/

Github:https://github.com/humanfromearth/django-stdimage