1

I have a webscraping app that downloads images from a website and stores it in an ImageField of one of my models.

models.py

class Article(models.Model):
    title = models.CharField('Title', max_length=300)
    url = models.CharField('URL', max_length=200)
    hero_image = models.ImageField(upload_to='pictures', max_length=255)

My hero_image field looks like this in my project: "http://localhost:8000/media/pictures/gettyimages-585288019.jpgw210h158crop1quality85stripall"

And the images are stored at myproject/myproject/pictures:

myproject
├── myproject
│   ├── settings.py
├── pictures
├── manage.py

When I click the sample link above I automatically download the image, but instead I would like to show the image in the browser.

What I've done so far

myproject/urls.py

    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'', include('core.urls')),
]
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

MEDIA_URL = '/media/'

There are a lot of topics similar to my question on SO but I've read a bunch of them and still can't find one that seems to help me solve my problem.

Gabriel Belini
  • 760
  • 1
  • 13
  • 32

1 Answers1

1

When I click the sample link above I automatically download the image, but instead I would like to show the image in the browser.

This is determined by the web server. If you set the HTTP header Content-Disposition: inline, it's an instruction to the web browser to open the image in the browser instead of treating it as a file download.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition

Most web servers such as Apache or Nginx will set this header by default for all image files.

If you want to add the Content-Disposition header to files served by the runserver development server, you might have to override the default method. See this question for details.

django dev server, adding headers to static files

Håken Lid
  • 22,318
  • 9
  • 52
  • 67