Django is not serving staticfiles - django

I would like to use django staticfiles, but unfortunately I can't get it to serve to images locally.
This is what I have done so far:
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'content.apps.ContentConfig',
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
When I do a print(os.path.join(BASE_DIR, 'staticfiles')) I see the correct local path.
urls.py:
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
import content.views
urlpatterns = [
path('admin/', admin.site.urls),
path('', content.views.index, name='index'),
path('/about', content.views.about, name='about'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
templates:
{% load static %}
...
{% static "css/master.css" %}
resolves to
/static/css/master.css
[EDIT]
URL PATTERN looks like this
Using the URLconf defined in website.urls, Django tried these URL
patterns, in this order:
admin/
[name='index']
/about [name='about']
^static/(?P<path>.*)$
Opening a file directly ends up to a 404-django-page.
After that, I ran ./manage.py collectstatic successfully.
I am using the Django Dev server e.g. ./manage.py runserver...
I am maybe missing something, just need an additional pair of eyes. Thanks.

Solved it by removing
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
and replacing it with
STATICFILES_DIRS = (os.path.join(BASE_DIR, "staticfiles"),)

Related

Django deployment Failed to load resource: the server responded with a status of 404 (Not Found)

I have some product pictures uploaded in media folder that displays fine in development server, but after deployment I receive the 404 ressource not found error.
In settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'node_modules')]
STATIC_ROOT = os.path.join(BASE_DIR, 'productionStatic')
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
In urls.py
from django.contrib import admin
from django.urls import path
from index import views
from index.views import indexPage, hdnytorv
from webshopRestaurant.views import hd2900_webshop_Main, AddressCheckForDeliverability, ChangeItemQuantity
from webshopCustomer.views import TakeawayCheckout, totalPriceDeliveryPossible, DeliveryForm, PickUpForm, localDeliveryCheckoutAddressCheck, Payment, PaymentComplete
from django.conf import settings
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = [
path('admin/', admin.site.urls),
path('', indexPage.as_view(), name = 'index'),
path('hdnytorv', hdnytorv.as_view(), name='hdnytorv'),
path('hd2900', views.hd2900.as_view(), name='hd2900'),
path('hd2900_takeaway_webshop', hd2900_webshop_Main.as_view(), name="hd2900_takeaway_webshop"),
path('check-address-for-deliverable', AddressCheckForDeliverability.as_view()),
path('changeItemQuantityInBasket', ChangeItemQuantity.as_view()),
path('isPriceAboveDeliveryLimit', totalPriceDeliveryPossible.as_view()),
path('hdbynight', views.hdbynight.as_view(), name='hdbynight'),
path('takeawayCheckout', TakeawayCheckout.as_view()),
path('deliveryFormCheckout', DeliveryForm.as_view()),
path('pickupFormCheckout', PickUpForm.as_view()),
path('local_delivery_checkout_is_address_deliverable', localDeliveryCheckoutAddressCheck.as_view()),
path('localDeliveryPayment', Payment.as_view()),
path('paymentComplete', PaymentComplete.as_view()),
]
#When in production medida url must always be added to urlpatterns
#if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
To display the product in view I have in my html template
<img class="card-img embed-responsive-item" src="{% get_media_prefix %}{{ item.product.image_path }}" alt="{{item.meta_description}}">
The pictures are uploaded to this location django_project_folder/media/productImages. I have assured that it is owned by www-data group and also media and all subfolders have 775 access rights. In development server the images shows up all right but in production I got 404 not found error.
This issue is a duplicate. See the answer here I fixed it by adding in urls.py
from django.urls.conf import re_path
from django.views.static import serve
re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),

No CSS in Admin panel in Azure App Service hosted Django APP

I cant figure out how to make Azure App Service use css for admin panel.
In settings.py I included these:
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
But somehow css is still not working for the admin panel.
How can I fix this? As far as I know Oryx which works under Azure App Service should automatically run
python manage.py collectstatic
Any ideas?
EDIT:
Installed apps
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'licenses_api',
]
There are something to check might help:
Click F12 on your Admin page to check if it is the 404 Not Found error.
Check the static files exist in your azure web app or not. You could see it in https://{your-web-app}.scm.azurewebsites.net/wwwroot/ site.
Check if your file structure match with the settings.py. Any spell error would make the static file not found.
If your file exists well, you should check if you use them correctly in your code like this answer. Here is how he use:
from django.conf.urls.static import static
urlpatterns = [
path('myapp/', include('myapp.urls')),
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Firstly try to add these code lines to
settings.py
STATIC_URL = '/static/'
if DEBUG:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Then import these lines to the
urls.py
from django.conf.urls.static import static
from django.conf import settings
from django.conf.urls import url
from django.views.static import serve
Finaly you have to add these lines to urlpatterns in
urls.py
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
(If you have not already created a static file please make sure to create one before you try this)
It's worked severl times for me and hope this will work for you too 😊

Django 1.8 Why local static requests raise 404?

Project name is exam. I place simple.css file in exam/static/css/. When I request http://127.0.0.1:8000/static/css/simple.css, it returns 404 error, saying 'css\simple.css' could not be found. The settings seem all right. In production environment the static requests are all right with nginx.
Related infomation:
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))).replace('\\','/')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [
],
'APP_DIRS': True,
},
]
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\','/')
STATIC_ROOT = os.path.join(BASE_DIR, "static").replace('\\','/')
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
)
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL , document_root = settings.MEDIA_ROOT )
Perhaps you're missing the STATICFILES_DIRS setting.
When in production, python manage.py collectstatic moves all static files inside STATIC_ROOT directory so nginx can look up here for them, however in dev mode, django needs to know where the static files are, and use STATICFILES_DIRS tuple for that.
If you have these files inside exam/static, your STATICFILES_DIRS should looks like:
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
If you are using ./manage runserver then you're missing STATICFILES_DIRS.
For nginx/gunicorn http://nginx.com/resources/admin-guide/serving-static-content/. Also Django White Noise

serving static files django development

I know a million people have asked this, and I've read and read but still cannot get this to work (I think that says something about the documentation cough cough).
ONE. CSS:
Here are my settings:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'))
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static")
STATIC_ROOT = '/static/'
STATIC_URL = '/static/'
also relevant:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'blog',
)
My templates are serving up just fine, while my css is not. its located in static/originaltheme.css
I've tried both:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}originaltheme.css">
and
<link rel="stylesheet" type="text/css" href="/static/originaltheme.css">
TWO. Also, is there a way to get hardcoded urls to display? for example, lets say the content of a blog post has a hardcoded url to /static/img1.jpg, how can I do that? All of the documention points to {{ static_url }}, but im guessing that that wont get evaluated when returned from a text field of a database...
is there something to do with my urls?
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'nickswebsite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', 'blog.views.index'),
url(r'^blog/view/(?P<slug>[^\.]+)',
'blog.views.view_post',
name='view_blog_post'),
url(r'^blog/category/(?P<slug>[^\.]+)',
'blog.views.view_category',
name='view_blog_category'),
url(r'^admin/', include(admin.site.urls)),
)
EDIT:
I tried doing this is in the urls:
urlpatterns = patterns('',
url(r'^$', 'blog.views.index'),
url(r'^blog/view/(?P<slug>[^\.]+)',
'blog.views.view_post',
name='view_blog_post'),
url(r'^blog/category/(?P<slug>[^\.]+)',
'blog.views.view_category',
name='view_blog_category'),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=setting.STATIC_ROOT)
urlpatterns += staticfiles_urlpatterns()
but im getting a "settings" undefined error. I tried to import settings and im still getting an error.
Edit
Okay, the documentation for serving static off development server is HORRIBLE. Whoever wrote it should really rewrite it. This guy is the only person in the entire world who seems to explain this clearly: http://agiliq.com/blog/2013/03/serving-static-files-in-django/#servee
You DO need these in the settings.py (why arent they included in the initial installaion??? what genius...):
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
You do NOT need these:
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static")
STATIC_ROOT = '/static/'
You do NOT need:
manage.py collectstatic
http://agiliq.com/blog/2013/03/serving-static-files-in-django/#servee:
Points to be noted
We did not make any changes to any of the static settings provided by Django to us. We left the static settings as they were in default settings.py provided by Django.
You don't need any change in your urls.py for serving your static files in development. You don't need to add staticfiles_urlpatterns(). Many a times, I got confused with this.
You do not need python manage.py collectstatic for serving static files in development.
I also fought against this particular problem. And finally came up with this blog post
Actually you don't need collectstatic , STATICFILES_FINDER and django.contrib.staticfiles. They are all related. Read the blog post
I added these lines to the bottom of my url.py:
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
And this in my settings.py:
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Did you use:
./manage.py collectstatic
Also your STATIC_ROOT should be absolute path to the directory static files should be collected to:
STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, "static"))
This is what I did for Django 2.0 using the above answers. So you'll want a system that makes deployment easy.
settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Serve Static in Development
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATICFILES_DIRS = [os.path.join(BASE_DIR, "appName/static/appName")]
# Serve static in production
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Then made a directory ~/documentRoot/appName/static/appName/ and copied my png into it. Then in my template:
<head>
<bootstrap,jquery,etc...>
{% load staticfiles %}
</head>
<body>
<img class="mb-4" src="{% static "myImage.png" %}" alt="" width="72" height="72">
</body>
Then when you want to deploy you just run collectstatic and they'll be served in one spot. Each time you add an app, add to that list of static dirs.

django css and js files

I am unable to use CSS and JS files in my django project.
Folder structure:
mysite/
mysite/mysite/settings.py
mysite/mysite/templates/base.html
mysite/mysite/assets/css/...
settings.py
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = 'static'
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',...)
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
base.html
running python manage.py collectstatic returns:
"Your STATICFILES_DIRS setting is not a tuple or list; "
django.core.exceptions.ImproperlyConfigured: Your STATICFILES_DIRS setting is not a tuple or list; perhaps you forgot a trailing comma?
You never manually put anything STATIC_ROOT. It is only a dumping ground for collectstatic in production; it shouldn't even exist in development.
All of your static resources need to go in one of your apps' static directories, or if you need project-wide resources, you must create an entirely different directory for that is not the same as either MEDIA_ROOT or STATIC_ROOT and add it to STATICFILES_DIRS:
STATICFILES_DIRS = (
os.path.join(PROJECT_PATH, 'assets'),
)
You can call it whatever you want; I typically use "assets". Just don't name it "static", "media", "site_media", etc., just to avoid confusion.