【发布时间】:2020-11-05 19:07:06
【问题描述】:
我正在尝试使用一个表单来从将要上传的图像中生成缩略图
我将使用 sorl 生成拇指,并且我遵循以下文档:
- Django 多文件上传:https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/
- Sorl 低级 API:https://sorl-thumbnail.readthedocs.io/en/latest/examples.html
当我尝试生成缩略图时,我得到了错误
not enough values to unpack (expected 2, got 1)
我不明白我做错了什么,总而言之,我上传了图像并将其保存在我的根目录中,然后我尝试创建拇指
还有没有办法避免将原始图像保存在根目录中?我打算将图片和拇指都发送到谷歌云存储
我的forms.py:
from django import forms
class FileFieldForm(forms.Form):
file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
我的html文件:upload.html
<html>
<head></head>
<body>
<h3>Read File Content</h3>
<form enctype="multipart/form-data" action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Save">
</form>
</body>
</html>
我的 views.py 看起来像:
from sorl.thumbnail import ImageField, get_thumbnail
from .forms import FileFieldForm
class FileFieldView(FormView):
form_class = FileFieldForm
template_name = 'app_workflow/upload.html' # Replace with your template.
success_url = '/photo' # Replace with your URL or reverse().
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
files = request.FILES.getlist('file_field')
if form.is_valid():
for f in files:
with open(f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
im = get_thumbnail(f.name, '100x100', crop='center', quality=99)
return self.form_valid(form)
else:
return self.form_invalid(form)
【问题讨论】:
标签: python django django-forms django-file-upload sorl-thumbnail