繁体   English   中英

Django中的文件上传/处理

[英]File uploading/handling in Django

我已经连续进行了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次,这(在我看来)是我最接近的成功。

考虑尝试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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM