How to serve static files in django 3.1 - python

I'm use django 3.1 when I have the option DEBUG = True in my settings.py the static files are serve fine, but when I use DEBUG = False the static files are not serve I all ready try with this solution:
404 Static file not found - Django
In the answer like in de official docs of django use this:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
But still doesn´t works. Someone have any idea why still doesn't works.

You can add this
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = (
os.path.join(BASE_DIR, 'staticfiles')
)
MEDIA_URL = '/media/'
MEDIA_ROOT = (
os.path.join(BASE_DIR, 'media')
)
mkdir static
python manager.py collectstatic --noinput
python manager.py runserver
it works

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

Django Oscar Image saved in cache folder but not showing

Could anyone point me the direction to solve the image not displaying properly, since the image was saved in cache folder with 500 error. I am not sure if it is to due to permission or something deeper?
This is what I had configure but not sure if I doing it right.
URLS.py:
from django.apps import apps
from django.urls import include, path
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from oscar.views import handler403, handler404, handler500
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(apps.get_app_config('oscar').urls[0])),
]
if settings.DEBUG:
import debug_toolbar
# Server statics and uploaded media
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# Allow error pages to be tested
urlpatterns += [
path('403', handler403, {'exception': Exception()}),
path('404', handler404, {'exception': Exception()}),
path('500', handler500),
path('__debug__/', include(debug_toolbar.urls)),
]
Setting.py:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_ROOT = '/media/'
MEDIA_URL = '/media/'
THUMBNAIL_DEBUG = DEBUG
THUMBNAIL_KEY_PREFIX = 'oscar-sandbox'
THUMBNAIL_KVSTORE = env(
'THUMBNAIL_KVSTORE',
default='sorl.thumbnail.kvstores.cached_db_kvstore.KVStore')
THUMBNAIL_REDIS_URL = env('THUMBNAIL_REDIS_URL', default=None)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
I had the same problem. I was helped by adding in urls.py applications
url string
templates += static (settings. MEDIA_URL, document_root=settings. MEDIA_ROOT)
In settings.py were also added:
# Path helper
location = lambda x: os.path.join(
os.path.dirname(os.path.realpath(__file__)), x)
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = location("public/media")
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATIC_ROOT = location('public/static')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_DIRS = (
location('static/'),
)

Django 3.1 not serving media files correctly

I have a project running in Django 3.1, and suddenly it has started to fail serving media files (static files uploaded by users), even though I haven't changed anything in settings.py or elsewhere.
My main urls.py:
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('cart/', include('cart.urls', namespace='cart')),
path('', include('contacts.urls', namespace='contacts')),
path('customers/', include('customers.urls', namespace='customers')),
path('orders/', include('orders.urls', namespace='orders')),
path('account/', include('account.urls')),
path('', include('catalog.urls', namespace='catalog')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
From my settings.py:
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath( os.path.join(__file__, os.pardir))))
DEBUG = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
STATICFILES_DIRS = ( os.path.join('static'), )
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
I don't know and can't figure out where the mistake is, but runserver just keeps throwing 404 when trying to load media files, even though static files (CSS/JS) are being served correctly.
your Urls looks fine, although i notes that you missing from django.contrib import admin.
About your settings, here is mine that works just fine for me.
Add import os to your settings.py if it is not there.

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

Categories

Resources