1

I'm working on a news website using django in which I manage data about articles I have id, content,title,category and image which is a FileField

class Article(models.Model):

    id=models.AutoField(primary_key=True)
    title=models.CharField(max_length=100,null=False,blank=False)
    category=models.ForeignKey(Category,null=False,blank=False)
    date=models.DateTimeField(auto_now_add=True)
    content = models.TextField(null=False, blank=False)
    resume=models.CharField(null=False,blank=False,max_length=400)
    image = models.FileField(verbose_name=blank=True)

I created an add form which contains data about article

The form contains an input file

<input type="file" name="image">

The form is correctly submitting data and the image is successfully stored. However I noticed that this input works only with local images. It only works if I manually select the image from my computer or I drag it to the input.

If I drag an image from a website to the input it doesn't work.

I would like to know if there's a solution that I can use to drag an image from another website to the file input, because each time I need to submit an image I need to download it.

Any help would be appreciated

1 Answer 1

1

you need to get the url of the image and download it using urllib2 here is a simple example of how to get the url using javascript

$(document).on('dragover', function(e) {e.preventDefault();return false;});
    $(document).on('drop', function(e) {
        e.preventDefault();
        e.originalEvent.dataTransfer.items[0].getAsString(function(url){
            alert(url);
    });
});

and here is how you can download it and use it in your module

from urllib.parse import urlparse
import requests
from django.core.files.base import ContentFile
from myapp.models import Photo

img_url = "url" #request.POST["url"] for example
name = urlparse(img_url).path.split('/')[-1]

photo = Article() # you need to use ImageFiled if it's just an image in your model

response = requests.get(img_url)
if response.status_code == 200:
    photo.image.save(name, ContentFile(response.content), save=True)

Not the answer you're looking for? Browse other questions tagged or ask your own question.