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