I have a modelform that looks like this:
我有一个如下所示的模型:
class NewSongForm(forms.ModelForm):
image_url = forms.URLField(required=False)
def save(self, *args, **kwargs):
url = self.cleaned_data['image_url']
if not self.cleaned_data['image'] and url:
# no file was uploaded, but a url was given
# fetch the image from the url and use that.
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(urllib2.urlopen(url).read())
img_temp.flush()
self.cleaned_data['image'] = File(img_temp)
return super(NewSongForm, self).save(*args, **kwargs)
class Meta:
model = Song
fields = ('image', ) # is an ImageField
Basically a user can upload either an image from the image
field (A ImageField), or they can supply a url through the image_url
field, (which is a URLField)
基本上用户可以从图像字段(A ImageField)上传图像,或者他们可以通过image_url字段提供网址(这是一个URLField)
This code looks like it should work, but it doesn't. I got the specific method for saving the url to File
via urllib2 from this stack overflow answer: Django: add image in an ImageField from image url
这段代码看起来应该可行,但事实并非如此。我从这个堆栈溢出答案得到了通过urllib2将url保存到File的具体方法:Django:从图像url在ImageField中添加图像
1 个解决方案
#1
Solved my own problem. I needed to place the download code into the clean method instead of the save method.
解决了我自己的问题。我需要将下载代码放入clean方法而不是save方法。
class NewSongForm(forms.ModelForm):
image_url = forms.URLField(required=False)
def clean(self, *args, **kwargs):
all_data = self.cleaned_data
url = all_data['image_url']
image = all_data['image']
if not image and url:
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(urllib2.urlopen(url).read())
img_temp.flush()
all_data['image'] = File(img_temp)
return all_data
class Meta:
model = Song
fields = ('image', ) # is an ImageField
#1
Solved my own problem. I needed to place the download code into the clean method instead of the save method.
解决了我自己的问题。我需要将下载代码放入clean方法而不是save方法。
class NewSongForm(forms.ModelForm):
image_url = forms.URLField(required=False)
def clean(self, *args, **kwargs):
all_data = self.cleaned_data
url = all_data['image_url']
image = all_data['image']
if not image and url:
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(urllib2.urlopen(url).read())
img_temp.flush()
all_data['image'] = File(img_temp)
return all_data
class Meta:
model = Song
fields = ('image', ) # is an ImageField