Reputation: 35150
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)
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
Upvotes: 2
Views: 1225
Reputation: 35150
Solved my own problem. I needed to place the download code into the clean method instead of the save method.
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
Upvotes: 2