Images(Media) not displaying on django-heroku server - python

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)

Related

How to serve static files (like images) in a combined django-react application

This is the first web application I'm developing by combining django and reactjs, in fact react is new to me.
Please if my approach is wrong I'm open for correction.
When developing with purely django, I find no difficulty with static and media files.
It is clear that the elements involved are the media root and static root,
respectively. In that case, all I need to do is to specify the static/media root in the
settings.py in the django app as shown below:
settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/images/'
urls.py
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
However, when I combine django and react the configuration changes since django is configured
to look at index.html file in react, in which case an additional element called STATICFILES DIRS
is added to the seetings.py file to specify the path to react index.html. In fact, my django app
configuration looks like this when I combine django and react:
settings.py
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'build/static')]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/images/'
urls.py
urlpatterns = [
...
re_path(r'^.*', TemplateView.as_view(template_name='index.html'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'build')],
...
]
Everything works well as when I'm developing purely with django except that when I combine django and react in development the images I upload refuse to displayed
on the browser since any path that does not match with the specified paths in urlpattern are redirected
to react. re_path(r'^.*', TemplateView.as_view(template_name='index.html')) So the image path is being redirected. When I click the image link in the admin file, instead of
the image to get displayed, I'm redirected to react also. I have made research online but I can't find any resources
that explained properly how to configure the django static root and media root to be able to serve files (
like images uploaded to the database) content.
Please, do I display images and media on the browser? In production, I would like to serve static files of the
django-react app with aws s3 bucket
Check that you have added the build folder to installed apps
INSTALLED_APPS = [ build, ]
If DEBUG use STATICFILES_DIRS else use STATIC_ROOT. Add this code in the settings.py file.
if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] else: STATIC_ROOT = os.path.join(BASE_DIR, 'static')
In the urls.py file
urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))]
Then run python manage.py collectstatic
You should also install whitenoise pip install whitenoise

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'

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

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')

Django : Static content not found

I have been breaking my head over this for a full day but can't figure out the problem. It happened after I copied my project from one machine to another.
Settings.py
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
Mentioned 'django.contrib.staticfiles' in INSTALLED_APPS as well.
Folder structure :
Django-Projects (root)
project
app
static
css
home.css
js
manage.py
Template :
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/home.css' %}">
urls.py
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'', include('app.urls')),
)
It throws an error in the console on opening the template :
GET http://127.0.0.1:8000/static/css/home.css
Failed to load resource: the server responded with a status of 404 (NOT FOUND)
What might be wrong here ? Please help me out. Much thanks!
In your settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_URL = '/static/'
Then in your template file:
<link rel="stylesheet" href="{{ STATIC_URL }}css/home.css">
With the directory root structure that you have shown, I think the above setting should work. Have not tested it though. Let me know if it works.
set DEBUG=True and see if it works .. this means, django will serve your static files, and not httpserver which in this case doesnt exist since you run the app locally.
I had researched this problem for a full day. This will be okay:
DEBUG = True
ALLOWED_HOSTS = []
Django default BASE_DIR will search static content for you. But in your case you changed the way before initial project. So for that in your case you have to change your BASE_DIR like this .. then only static file will serve correctly
BASE_DIR = os.path.dirname(os.path.abspath(__file__) + '../../../')
Updated:
I didn't see that comment. ! DEBUG = True only for development and You set as False so will django use STATIC_ROOT = 'staticfiles' to serve the static content on the production environment ... Thank you
You don't have to refer to STATIC_ROOT = 'staticfiles'
Just Like that:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
I had the same issue in Django.
I added to my settings: STATIC_ROOT = 'static/'
It was the only problem.

How do I display an image on my webpage in Django?

I want to display an image on my website. I've been looking through the Django documentation and the other posts on stackoverflow, but I haven't gotten this to work.
I have an image name 'under-construction.jpg'. It lives in the /home/di/mysite/myapp/static/images directory.
I have a template like this:
<img src="{{ STATIC_URL }}images/under_construction.jpg" alt="Hi!" />
in my views.py I have this:
def under_construction(request):
return render(request, 'under_construction.html')
In my settings.py, I have this:
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/home/di/mysite/myapp/static',
'/home/di/mysite/myapp/static/images',
)
I executed ./manage.py collectstatic and it put a lot of files in /home/di/mysite/admin and /home/di/mysite/images. What do I have to do get my image to show up?
All you need to do is edit settings.py to be as the 4 following points and create a new folder (static) in the same folder settings.py is located
in the folder static you can create another folder (images) in it you can put the (under_constructioon.jpg)
STATICFILES_DIRS = (os.path.join( os.path.dirname( __file__ ), 'static' ),)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',)
STATIC_URL = '/static/'
STATIC_ROOT = ''
after you're done with the prev. points you can write
<img src="{{ STATIC_URL }}images/under_construction.jpg" alt="Hi!" />
I have faced same problem displaying the static image. suffered a lot and spent a lot lot of time in this regard. So thought to share my settings.
settings.py
STATIC_ROOT = ''
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
import os.path
STATICFILES_DIRS = (
"D:/temp/workspace/offeronline/media",
(os.path.join( os.path.dirname( __file__ ), 'static' )),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
urls.py
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ... and at the end of the file add the following line
urlpatterns += staticfiles_urlpatterns()
and finally added the following code to the template tag and it worked
<img src="{{ STATIC_URL }}images/i1.png" />
I have solved that problem like this.
STATIC_ROOT = '/path/to/project/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
)
Django will not directly get files directly even you do this. You need to link this static directory for each application of yours. Just go to the django app dir run following command..
cd /path/to/project/my_proj/my_app
ln -s /path/to/project/static/
This will work only in debug mod. You need to set DEBUG = true in settings.py file. This should work with django's development server.
Django won't serve any static file in production mod. You need to serve static files with web-server in production mod.
More information can be found here..
Django does support static files during development, You can use the django.views.static.serve() method in view to serve media files.
But using this method is inefficient and insecure for production setting.
for Production setting in Apache
https://docs.djangoproject.com/en/1.2/howto/deployment/modpython/#serving-media-files
set STATIC_ROOT = /path/to/copy/files/to
have you added
urlpatterns += patterns('django.contrib.staticfiles.views', url(r'^static/(?P<path>.*)$', 'serve'),
or you can also do this
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()
and of course try not to server static files through django it does have some overhead instead configure your http server to serve them, assuming you have an http server (nginx is quite good).

Categories

Resources