Django 3.1 not serving media files correctly - python

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.

Related

Django media file page not found

So, I'm trying to follow Django documentation about the static files and media files
I have a clean Django installation and I want to add the media folder. What I've done? I've changed the urls.py inside the project (not the app) and the settings.py as below
settings.py
STATIC_URL = 'static/'
MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / "media"
STATICFILES_DIRS = [
BASE_DIR / "static",
]
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
But I got the
Page not found (404) Request Method: GET Request
URL: http://127.0.0.1:8000/ Using the URLconf defined in
web_project.urls, Django tried these URL patterns, in this order:
admin/ ^media/(?P.*)$ The empty path didn’t match any of these.
I've also tried adding the 'django.template.context_processors.media' into TEMPLATES and using os as below
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
but nothing changes
What it could be?
Getting this error is the expected behavior because when you add a path to urlpatterns in urls.py in your example + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) you'll no more get access to http://127.0.0.1:8000/ (it just renders a “Congratulations!” page, with a rocket taking off. It worked! ) unless you specify a view to this empty path (which you didn't)
In your case, there is no URL leading to http://127.0.0.1:8000/ . the only paths you get access to are :
1- http://127.0.0.1:8000/admin/ for the admin page
2 - http://127.0.0.1:8000/media/(?P<path>.*)$ to access you media files
for example, if you have an image img.png in media folder you can access http://127.0.0.1:8000/media/img.png and view your image
The static function is only intended to serve static files during development and is not suitable for serving user-uploaded media files.
Try to make a condition check that whether DEBUG=True or not so:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

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

How to serve static files in django 3.1

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

Only Django Admin pages visible while rest of Site blank in production

Im trying to host my site on heroku on my localhost my project is fine with no issues , on deploying it all I get are blank pages (I inspected it and elements are shown but nothing is visible on webpage)apart from admin pages I installed all the necessary packages as I was deploying that is to say gunicorn and whitenoise as well as setting STATIC_ROOT and STATICFILES_STORAGE . I at first set DISABLE_COLLECTSTATIC = 1 and later set it to 0 when deploying, I have failed to see any error that might be causing the issue
some of my files for context
settings
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_dev')]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
urls
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import handler404
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('user.urls')),
path('users/', include('django.contrib.auth.urls')),
path('accounts/', include('allauth.urls')),
path('', include('pages.urls')),
path('store/', include('store.urls')),
#path("djangorave/", include("djangorave.urls", namespace="djangorave")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#error handlers
handler404 = 'store.views.error_404'
#handler500 = 'store.views.my_custom_error_view'

Django CKEditor Image Uploads not appearing

This is a duplicate of Django Ckeditor image browser not finding images, but I believe the answer there is wrong (there is an obvious bug in it with an undefined variable, not to mention the lack of Python indentation).
I'm using Django CKEditor 5.0.3 and Django 1.9.6. I am able to upload images in my admin, but they appear as a red X within the admin and do not appear on my site.
I'm still struggling a bit with MEDIA_ROOT and whatnot, but I think I have it right:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
MEDIA_URL = "image_upload/"
MEDIA_ROOT = os.path.join(BASE_DIR, "image_upload")
CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_UPLOAD_SLUGIFY_FILENAME = False
My urls.py, including my attempt at cleaning up the linked answer:
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from mainsite.views import HomepageView, AboutView, ContactView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^admin/', admin.site.urls, name="admin"),
url(r'^$', HomepageView.as_view(), name="homepage"),
url(r'^about/', AboutView.as_view(), name="about"),
url(r'^contact/', ContactView.as_view(), name="contact"),
url(r'^blog/', include("blog.urls", namespace="blog")),
url(r'^ckeditor/', include('ckeditor_uploader.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$',
'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}
),
]
urlpatterns += staticfiles_urlpatterns()
Using CKEDITOR_UPLOAD_PATH = 'uploads/' makes django-ckeditor to upload an image to /media/uploads/, like:
settings.py:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static/'),
]
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
CKEDITOR_UPLOAD_PATH = 'uploads/'
When using the Django's dev server, static files are served by default but not media files, so you can force the server to consider them, the url configuration below should work.
urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.views.static import serve
from .views import HomeView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', HomeView.as_view(), name='home'),
url(r'^ckeditor/', include('ckeditor_uploader.urls')),
# serving media files only on debug mode
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT
}),
]
The missing function patterns from the old example was an old function I believe used on Django 1.6 or 1.7.
After installing ckeditor, perform the following :
In Settings.py:
add 'ckeditor' and 'ckeditor_uploader' into INSTALLED_APPS.
Add CKEDITOR_UPLOAD_PATH = 'uploads_directory/'
(Do not join MEDIA_ROOT with the upload_directory, ckeditor will take the MEDIA_ROOT as its root upload directory)
In your models files:
USE : from ckeditor_uploader import RichTextUploadingField and modify your required model field to type RichTextUploadingField
In urls.py:
add re_path(r'^ckeditor/', include('ckeditor_uploader.urls')) into urlpatterns
Using Django 1.8 with django-ckeditor 5.3.0, I was getting the exact same symptoms as those above (uploading files worked, but the src attribute of the <img> tag was set incorrectly, causing a red "X" in the preview and broken image links upon publication).
In my case, however, I didn't have to change anything in urls.py. My problem was that I had:
CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "ckeditor")
So my mistake was giving CKEDITOR_UPLOAD_PATH the path where I wanted ckeditor to upload to (logical, no?).
The fix was to change the above line to
CKEDITOR_UPLOAD_PATH = "ckeditor"
In hindsight I can see how this allows django-ckeditor the ability to use the MEDIA_ROOT for uploading and the MEDIA_URL for serving. Still I thought someone should say it: "Don't use the full path when setting CKEDITOR_UPLOAD_PATH!"
I hope this saves others some time.
For Django 4 the steps to enable image or file upload in django-ckeditor is:
1. Install django-ckeditor
pip install django-ckeditor
2. Update settings.py
Add file upload path:
CKEDITOR_UPLOAD_PATH = "uploads/"
Add ckeditor,ckeditor_uploader in INSTALLED_APPS:
INSTALLED_APPS = [
...
# plugins
'ckeditor',
'ckeditor_uploader'
]
3. Update urls.py
Add path('ckeditor/', include('ckeditor_uploader.urls')) in urlpatterns:
urlpatterns = [
...
path('ckeditor/', include('ckeditor_uploader.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
4. Use RichTextUploadingField in models
from ckeditor_uploader.fields import RichTextUploadingField
class ResearchTopic(models.Model):
title = models.CharField(max_length=200)
description = RichTextUploadingField()
Tested with:
Django==4.0.4
django-ckeditor==6.4.0
References:
django-ckeditor documentation
The #Mohammed-tayab's solution worked for me with a little modification:
from ckeditor_uploader.fields import RichTextUploadingField

Categories

Resources