'AttributeError at /media/.. when requesting file in media folder Django development stage

When I am reqeuesting media files (.png in this case) in the media folder in development I get this error:

AttributeError at /media/test.png This FileResponse instance has no content attribute. Use streaming_content instead.

Request: http://localhost:8000/media/test.png

I added below to the url patterns:

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And below to the settings:

STATIC_ROOT = BASE_DIR / 'static'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'

Static files are working just fine.

What do I overlook? Thanks!



Solution 1:[1]

hello if you have debug set to True you have to use this:

first go to you settings and set all you static file directories in

STATICFILES_DIRS = [
list of your static file,.......,]

the second step you should have this in your urls.py

    urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATICFILES_DIRS[0])

note:there is a difference between static_root and staticfile_dirs

static_root is only used for production

this is my mail for more explanation :[email protected]

Solution 2:[2]

I found the problem. In the newer django version staticfiles are rendered with a streamingHttpResponse, this doesn't have a content attribute.

I found below code in my code that points to the (non existing) content attribute:

if b'<html' in response.content[:100].lower():

I added this to resolve the problem:

if not hasattr(response, 'content'):
    return response
if b'<html' in response.content[:100].lower():

Thanks all!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Tom