我正在尝试
1)拍摄上传的图像并用枕头将其更改为黑白
2)在视图中将原始文件保存到名为“file”的FileField
3)在视图中将黑白版本保存到ImageField,名为“thumbnail_225”
1和2工作得很好,但我似乎无法弄清楚#3。
非常感谢任何反馈。
查看
def archive_media_upload(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
m = form.save(commit=False)
m.user = request.user
m.type = 1
# create black and white
image = Image.open(m.file)
black_and_white = image.convert("L")
#HOW DO I SAVE/ASSIGN BW IMAGE TO the "thumbnail_225" ImageField?
m.save()
return HttpResponseRedirect(reverse('archive_media_archive'))
else:
form = UploadForm(initial={'user': request.user })
return render(request, 'archive_app/archive_media_upload.html', {'archive':True, 'show_upgrade_link': show_upgrade_link,'form': form})
模型
class Media(models.Model):
created_date = models.DateTimeField(default=datetime.now)
type = models.IntegerField(default=0)
user = models.ForeignKey(User)
title = models.CharField(max_length=255, blank=True)
file = models.FileField(upload_to=get_upload_file_name)
thumbnail_225 = models.ImageField(upload_to="thumbnail_images/", blank=True)
答案 0 :(得分:0)
为了简短起见,您正在寻找的是(我认为)clean
方法。您应该在表单中定义它:
类UploadForm(forms.Form):
thumbnail_225 = forms.ImageField()
...
def clean_thumbnail_225 (self):
thumbnail_225 = self.cleaned_data["thumbnail_225"]
image = Image.open()
black_and_white = image.convert("thumbnail_225")
...
# return the clean data...
注意上面的代码只是一般方案。它不会真正起作用,也不包含所有正确的逻辑和\或语法。它仅用于演示。完整提示可在DJANGO's form and field validation documentation.
中找到