我有一个在ImageField中拍摄图像的模型:
class Result(models.Model):
image = models.ImageField(upload_to=get_userphoto_upload_path)
我想要一个可以采用URL或图像的表单,并将图像透明地保存到模型中。
这就是我的想法:
class ResultForm(forms.ModelForm):
externalsource = forms.URLField(label='External URL', required=False)
def clean(self):
cleaned_data = super(ResultForm, self).clean()
externalsource = cleaned_data.get('externalsource', False)
if externalsource:
req = requests.get(externalsource)
image = StringIO(req.content)
self.image.save(image)
class Meta:
fields = ['image']
model = Result
我知道self.image.save(图像)不正确(self.image不存在)......如果是图像而不是表格,那就是我手动保存图像的方式。我不确定我应该在它的位置使用它。
答案 0 :(得分:0)
我认为您希望像以下一样 。注意,我没有运行它或测试它或任何东西。但它应该有希望让你走上正确的道路。
from django.core.files.uploadedfile import InMemoryUploadedFile
class ResultForm(forms.ModelForm):
externalsource = forms.URLField(label='External URL', required=False)
def clean(self):
cleaned_data = super(ResultForm, self).clean()
externalsource = cleaned_data.get('externalsource', False)
if externalsource:
req = requests.get(externalsource)
image = StringIO(req.content)
file = InMemoryUploadedFile(file=image, field_name=None, name=externalsource, content_type=req.content_type, size=req.size, charset=None)
# Oops, long time since I used Forms, don't know how to do FileFields in forms
# but something like you already wrote:
self.image.save(name=dirname(externalsource), content=file)
class Meta:
fields = ['image']
model = Result
所以基本上,只制作一个InMemoryUploadedFile并将图像填入其中,并将其保存在ImageField中。
实际上你也可以简化和使用SimpleUploadedFile()。
我现在也看到你在那里嵌入了另一个关于Forms和Models和FileFields的问题, - 我不记得怎么做了。 :P