heroku-django-uploaded image is not displayed if DEBUG=False - python

I deployed my Django app on heroku. Every thing is working fine except displaying images. Any uploaded image is not displayed if DEBUG=False.
settings.py
DEBUG = False
ALLOWED_HOSTS = ['salma-blog.herokuapp.com']
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATIC_ROOT = os.path.dirname(myblog.__file__)+'/static/'
STATIC_URL = '/static/'
#upload images
MEDIA_ROOT= os.path.dirname(myblog.__file__)+'/static/myblog/images'
MEDIA_URL='/images/'
urls.py
urlpatterns=[
...
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
image tag in my template
<img alt="img" src="/blog{{image}}"></a>

Whitenoise uses static file finders when DEBUG=True, so you most likely have a problem with your static file collection process.
Update your STATIC_ROOT and MEDIA_ROOT settings to a recommended method, such as:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'images')

Related

Media file not being found in production Django-Heroku: returns 404 error

I have some default images in my media folder in Djang. However, on my website, I cannot see the images being displayed and I get a 404 error.
Now my project folder tree is(project name is register):
register
-- live-static
---- static-root
---- media-root
------ defaults
and my media and static files settings are:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'live-static', 'media-root')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
And inside my urls.py in the same folder as wsgi.py I have:
urlpatterns = [
"""
My other urls
"""
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
My static files are loaded and the server can retrieve them, however, the images that I added to my folders in media-root are returning a 404 error by the server. Why is this happening as I have already also set STATICFILES_STORAGE as well?
This is something I got hung up on with my first Heroku deploy. Since Heroku projects run on dynos, they eventually go to sleep if there is not a request within a certain period of time. When the dyno restarts, it does not save the uploaded data. Here is a link to some information from Heroku: https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted
What I ended up doing is setting up an Amazon S3 bucket for storage of these files. Dennis Ivy did a video explaining how to do this: https://youtu.be/inQyZ7zFMHM
Update your setting file like this
there is no need to change any thing else
in urls.py change the urlpatterns to. remove STATIC_ROOT etc
+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in setting.py like this. remove other file settings like STATICFILES_STORAGE
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
#if your media folder is in public_html which contain the media file
MEDIA_ROOT = '/home/yourusername/public_html/media'
STATIC_ROOT = '/home/yourusername/public_html/static'
#if your media folder is in other_folder which contain the media file
MEDIA_ROOT = '/home/yourusername/other_folder /media'
STATIC_ROOT = '/home/yourusername/other_folder /static'

Images(Media) not displaying on django-heroku server

I had uploaded my site Django app on Heroku server when I upload image file is successfully uploaded and image path as per settings also fetch properly but the image is not displaying it give error media file not found in a server
this is settings media setting
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
this is in url.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('UserView.urls')),
path('caterer/',include('CaterView.urls')),
]
# if settings.MediaAllow:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
this is models.py
class TypeofFood(models.Model):
tyf_id = models.AutoField(primary_key=True,auto_created=True)
tyf_value = models.CharField(max_length=256)
tyf_image = models.ImageField(upload_to="typeoffood/", null=True, blank=True,default='default.jfif')
in template it fatch image like this
<center><img src="{{i.tyf_image.url}}" class="img-responsive" style="height: 200px; width: 200px; border-radius:50%" alt="Image of Caterers"></center>
heroku free storage is not allow media file store, that's why your media file will be deleted after upload
because it is like testing purpose, if you want to upload and store media file on heroku you can use third party like whitenoise
go to the link and learn how to use whitenoise to upload media file on heroku, you can check this link also.
happy codding
For heroku to serve static files you need to add whitenoise package too. Install it and add the necessary configurations.
MIDDLEWARE_CLASSES = (
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
'whitenoise.middleware.WhiteNoiseMiddleware',
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = os.path.join(BASE_DIR, "your_static_folder")
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "your_media_folder")
In your html, you will have to serve your image like so:
{% load static %}
<img src="{% static "images/hi.jpg" %}" alt="Hi!">
The "image.url" format in the html does not work on staticfiles/Heroku
I ran into a similar issue on Heroku, and solved my issue using these links below.
Here is a complete guide for serving images on Heroku:
https://github.com/codingforentrepreneurs/Guides/blob/master/all/Heroku_Django_Deployment_Guide.md
I would recommend going through the references also. These would be the references:
1) http://whitenoise.evans.io/en/stable/django.html
2) https://docs.djangoproject.com/en/3.0/howto/static-files/
3) https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#std:templatetag-static
1-Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
2-In your settings file, define STATIC_URL, for example:
STATIC_URL = '/static/'
3-In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE:
{% load static %}
<img src="{% static 'my_app/example.jpg' %}" alt="My image">
4-Store your static files in a folder called static in your app. For example: my_app/static/my_app/example.jpg.
From the Docs
The Heroku filesystem is ephemeral - that means that any changes to
the filesystem whilst the dyno is running only last until that dyno is
shut down or restarted. Each dyno boots with a clean copy of the
filesystem from the most recent deploy. This is similar to how many
container based systems, such as Docker, operate.
Hence you will need to use a third party static file storage service.
settings.py
DEBUG = True #I got the error beacuse i changed the DEBUG to False
MIDDLEWARE = [
...
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
import os
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('app_name.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

unable to serve Django media files on the server?

I am using a Django version - 2.0.6.
and running the server on google compute engine VM instance.
My apache files are not configured to server the production base and local settings differently.
Currently the settings are running from base.py and local.py.
I have configured my media and static files like this:
my settings module(both base.py and local.py):
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), "static-root")
MEDIA_URL = '/media/'
MEDIA_DIR = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), "media-root")
my urls.py:
urlpatterns = [
....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
When I try to upload any media file it does not get saved in the "MEDIA_ROOT" location rather it get saved in "MEDIA_DIR".
How to serve media_root and media_dir in production?(/var/www/venv)
Static files are functional.
Hierarchy:
/var/www/ ----->media-root
>static-root
>venv--->src--->manage.py
>media
>static
>other apps & settings

Display Static file Django and rest-framework

I need to Display the static file, I follow Django document but it is not displayed.
1.In Models file
image = models.ImageField(upload_to='images/')
2.In urls.py file
from django.conf import settings
from django.conf.urls.static import static
...
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
3.In settings.py file
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'lost_items/static/')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
finally, I run this command
python manage.py collectstatic
when I GET API, the image in this URL
"image": "http://localhost:8000/media/images/n73.jpg"
So, When I click on it, I get the page not found, and:
The current path, media/images/money.jpg, didn't match any of these.
I assume that the images was uploaded by the user.
add this to your urls.py
if settings.DEBUG is True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
All uploaded files or "media" will have the Media URL. It only makes sense that Media URL must be added to urls.py

ImproperlyConfigured("Empty static prefix not permitted")

I am using Django Rest Framework to upload images.
The upload is working fine and is getting uploaded under media folder.
But I am unable to make the media links browsable. It says Error 404.
To make them browsable these are the changes that I made.
In settings.py I added the following lines.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_URL = '/media/'
In url.py I added the following lines
if settings.DEBUG is True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
DEBUG is True in settings.py as it's not in production. It is on my local machine under development.
But when I am starting the server it is showing me the following error:-
ImproperlyConfigured :- Empty static prefix not permitted
Sorry guys! I found my own mistake. Instead of MEDIA_URL I was using STATIC_URL

Categories

Resources