django static files weird behaviour - django

in my settings.py I have:
import os
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
# ... #
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
# ... #
STATIC_URL = '/static/'
in my urls.py I have:
urlpatterns = patterns('',
url(r'^', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
and in my template:
<img src="{{ STATIC_URL }}images/myimage.png">
Which doesn't work. The weird thing is that if I change my settings.py:
STATIC_URL = 'static/'
and my template to:
<img src="/{{ STATIC_URL }}images/myimage.png">
does work!! I have been chasing round in circle to fix this, and I have looked at lots of forum posts, but I can't seem to figure out what I'm doing wrong.

if you use staticfiles app you don't need this (assuming you are using Django 1.3):
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
})
Its handled by the app automatically. Try to remove and see what happens.

Related

User uploaded images not serve after debug=false in django?

install whitenoise urls.py setting
urlpatterns += static(settings.STATIC_URL, document_root = STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root = MEDIA_ROOT)
urlpatterns += [re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }), ]
also configure static root and static url in settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/images/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_ROOT = BASE_DIR / '/static/images/'
STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'static'))]
In urls.py file:
add this:
from django.views.static import serve
and add those two urlpatterns:
re_path('media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT})
re_path('static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT})

Loading MEDIA_ROOT files with Django Webpack Loader

After I setup a vue frontend with a django webpack loader, the media files are not rendering.
settings.py
STATIC_URL = '/static/'
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
WEBPACK_LOADER = {
"DEFAULT": {
"BUNDLE_DIR_NAME": "dist/",
"STATS_FILE": os.path.join(BASE_DIR, "frontend", "webpack-stats.json"),
}
}
And urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include("companies.routes.urls")),
path('api/v2/', include("projects.routes.urls")),
path('accounts/register/', RegistrationView.as_view(
form_class=CompanyUserForm,
success_url="/",
), name="django_registration_register"),
path('accounts/', include("django_registration.backends.one_step.urls")),
path('accounts/', include("django.contrib.auth.urls")),
path('api-auth/', include("rest_framework.urls")),
path('api/rest_auth/', include("rest_auth.urls")),
path('api/rest_auth/django_registration/', include("rest_auth.registration.urls")),
re_path(r'^.*$', IndexTemplateView.as_view(), name="entry-point")
]
urlpatterns += [
re_path(r'^media/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT
}),
]
# adding the media root path.
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
But when I browse the media file url, image isn't rendering. The issue lies inside urlpatterns at this line re_path(r'^.*$', IndexTemplateView.as_view(), name="entry-point") when I comment out this part. I can see the image. But i need the re_path for the frontend view. How should fix this issue?
you need to serve your media files add this to your urls.py
from django.views.static import serve
urlpatterns += [
re_path(r'^media/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT
}),
]

django display uploaded by user images

I have ImageUploadField
I save images at my_project/forum_attachments directory.
But when I try to display them and see by this link: http://127.0.0.1:8000/forum_attachments/1466786056166112161_Nrns2WL.jpg
I get an error
Page not found (404) Request Method: GET Request
URL: http://127.0.0.1:8000/forum_attachments/1466786056166112161_Nrns2WL.jpg
What do I do?
UPD: urls.py:
urlpatterns = [
url(r'^polls/', include('some_app.urls')),
url(r'^$', views.index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^about/', views.about, name='about'),
url(r'^login/$', auth_views.login, name='login'),
url(r'^user_logout/$', views.user_logout, name='user_logout'),
url(r'^index_old/', views.index_old, name='index_old'),
url(r'^forum/', views.forum, name='forum'),
url(r'^vip/', views.vip, name='vip'),
url(r'^test/', views.test, name='test'),
url(r'^forum_new/', views.forum_new, name='forum_new'),
]
First set in settings.py:
MEDIA_URL = '/forum_attachments/'
Then in your main urls.py add following piece of code:
from django.conf.urls.static import static
from django.conf import settings
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In case you've not set your MEDIA_URL & MEDIA ROOT in settings or your local settings file, you should follow the below procedure.
Settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(PROJECT_PATH,'../media/')
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
STATIC_URL = '/static/'
Now in your Urls.py, do this:
from django.conf.urls.static import static
urlpatterns = [
url(r'^polls/', include('some_app.urls')),
url(r'^$', views.index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^about/', views.about, name='about'),
url(r'^login/$', auth_views.login, name='login'),
url(r'^user_logout/$', views.user_logout, name='user_logout'),
url(r'^index_old/', views.index_old, name='index_old'),
url(r'^forum/', views.forum, name='forum'),
url(r'^vip/', views.vip, name='vip'),
url(r'^test/', views.test, name='test'),
url(r'^forum_new/', views.forum_new, name='forum_new'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The 'static' was appended to the urlpatterns because your DEBUG might be set to True in your settings.py.

Serving static media directly from heroku with Django

Due to not being able to store TinyMCE js files on my S3 bucket due to origin problems i'm trying to get Heroku to serve them up.
Here's what I've attempted so far but no luck. The browser url looks good (http://www.mysite.com/media/js/tiny_mce/tiny_mce.js) but heroku doesn't serve them up and returns a 404.
Here's my code:
Settings.py
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/'
TINYMCE_JS_URL = MEDIA_URL + 'js/tiny_mce/tiny_mce.js'
TINYMCE_JS_ROOT = MEDIA_ROOT + 'js/tiny_mce'
urls.py
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_URL}))
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
I can serve static assets directly from heroku using following code:
settings.py:
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/'
TINYMCE_JS_URL = MEDIA_URL + 'js/tiny_mce/tiny_mce.js'
TINYMCE_JS_ROOT = MEDIA_ROOT + 'js/tiny_mce'
urls.py:
urlpatterns = patterns('',
...
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True, }),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True, }),
)
base.html:
<script type="text/javascript" src="{{ MEDIA_URL }}js/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
mode: "textareas",
theme: "advanced",
forced_root_block: false,
force_p_newlines : false,
force_br_newlines : true,
});
</script>
Ok got it working using the comments in a github discussion https://github.com/aljosa/django-tinymce/pull/15
Primarily I changed the urls.py:
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': '/app/.heroku/python/lib/python2.7/site-packages/tinymce/static/'}))
I've got a feeling this could be much better resolved but i'm out of ideas and this works
For Django >= 2.0.0, For serving MEDIA_URL directly from heroku you can use
from django.urls import include, path, re_path
from django.views.static import serve
urlpatterns = [
...
re_path(r'^media/(?P<path>.*)$', serve,
kwargs=dict(document_root=settings.MEDIA_ROOT)),
]
Remember, heroku removes MEDIA_ROOT folder with every deploy.
More info
https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted

Django: Migrating from MEDIA_URL to STATIC_URL

Since Django 1.3 the concept of STATIC_URL has been introduced to separate use media files from css and js files.
I have set my STATIC_ROOT = '/home/user/project/static/' and
STATIC_URL = '/static/'.
In my base.html, i have changed the path like this:
<link href="{{ STATIC_URL }}bootstrap/css/bootstrap.min.css" rel="stylesheet">
And in url.py I have added the following two lines:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
...
urlpatterns += staticfiles_urlpatterns()
My view renders the template with RequestCOntext:
return render(request, 'main_page.html', variables)
But in the development I still get 404 when running runserver.
[18/Aug/2012 17:12:04] "GET /static/jquery/jquery-1.8.0.min.js HTTP/1.1" 404 1682
What could I be missing?
settings.py
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'site_media')
MEDIA_URL = '/site_media/'
STATIC_URL = '/static/'
if DEBUG:
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
else:
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, 'static'),
)
urls.py
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
)
That should work :)