Upload pic from another website using django
I want to make an image uploader using images links on the internet (eq: wwww.google.com/image.jpg
). The user writes the previous url and then my model upload it.
This my code:
form
<input id="id_name" type="text" name="name" maxlength="255" value="www.example.com/main.jpg" />
view.py
def Post_date():
if request.method == 'POST':
form = Addamazon()
image_url = request.POST.get('image')
file = urllib.urlopen(image_url)
im = cStringIO.StringIO(file.read()) # constructs a StringIO holding the image
img = Image.open(im)
save = '/tmp/' + str(int(time.time())) + '.gif'
img.save(save)
form.image=save
if form.is_valid():
pic = form.save(commit=False)
pic.save()
models.py
class Pic(models.Model):
image = ImageWithThumbsField(upload_to='images', sizes=((128, 开发者_运维技巧128),))
The image uploads but if form.is_valid():
doesn't work and I don't know how to add it to the form data.
how i can assign the downloaded image to my form (form.image=save)?
What are you taking from the user input? Is it Image file or the image URL?
If it is image URL then, make the field a forms.URLField and do the post and save like you are doing now.
If it is a image file, then don't extract the image file from the POST request. After you take out the file, (via read()
) form.is_valid
fails because that field isn't present. Just do the form.save()
and the uploading to the right folder with right name, is taken care, for you.
Do not assign the binary image back to form.image. Instead, add a separate field on the model to store the content of the image, such as a FileField or ImageField, and then after checking if form.is_valid() you can do:
def Post_date():
if request.method == 'POST':
form = Addamazon()
image_url = request.POST.get('image')
file = urllib.urlopen(image_url)
data = cStringIO.StringIO(file.read())
name = str(int(time.time())) + '.gif'
if form.is_valid():
pic = form.save(commit=False)
pic.image.save(name, data)
pic.save()
精彩评论