Django 1.8 Cannot load the css template - python

I have CSS file at /ecomstore/static/css.css
I have already linked the css to the base.html within head tags by
<link rel="Stylesheet" type="text/css" href="/static/css.css" />
My urls.py file:
from django.conf.urls import include, url
from django.contrib import admin
from ecomstore import settings
from django.contrib.staticfiles import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^catalog/','preview.views.home'),
# url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
# { 'document_root' : '/home/yogesh/ecomstore/static' })
]
urlpatterns = [
# other commented code here
url(r'^catalog/?','preview.views.home'),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{ 'document_root' : '/home/yogesh/ecomstore/static/' }),
]
Settings.py file
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [os.path.join(CURRENT_PATH, 'templates')],
'DIRS': [os.path.join(BASE_DIR, 'templates/')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Static settings:
STATIC_URL = '/static/'
STATIC_ROOT = "/home/yogesh/ecomstore/static/"
Despite all this stuff i dont know why my css template is not loading. Also in the terminal i am getting the following indicating some sort of error.
[24/Nov/2015 11:11:36] "GET /static/css.css HTTP/1.1" 404 1735

Use {% static %} template tag:
{% load staticfiles %}
Configure static files dir in your settings and do not hardcode the path in your urlconf:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
'/var/www/static/',
)
Make sure you're serving static files during development:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Check that static file dir /home/yogesh/ecomstore/static/ is readable by your django process.

Static files
Store your files in /ecomstore/static/ecomstore/css.css instead of /ecomstore/static/css.css because Django look by default in all folders <app_name/static/<app_name>, then you don't have to had these folder in STATICFILES_DIRS variable.
Django documentation :
Store your static files in a folder called static in your app. For
example my_app/static/my_app/myimage.jpg.
Read this for more
information and configure your project : Managing static files
Templates
You did also a mistake in the configuration of your template. When you use os.path.json function, you don't have to have a / at the last folder. Just use os.path.join(BASE_DIR, 'templates')
Serving static file during development
Concerning serving static files, if you use the django built-in server, you don't have to configure anything, Django serve them by default. However, if you use gunicorn or uWSGI, yes you have to configure your project to serve static files.
You have to add this in your main <project_name>/<project_name>/urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Now, your server will server static file based on STATIC_URL that you configured in your <project_name>/<project_name>/settings.py file.
Read this for more information : Serving static files during development

Related

Static CSS files not updating/loading in Django project

Problem: None of the changes I'm making to my CSS files are being applied to my HTML pages. And when I try and make new HTML/CSS files I get errors when I inspect the page in developer mode. The errors are saying they can't find my CSS files.
Exact error when I inspect my page in developer mode
GET http://127.0.0.1:8000/static/css/other.css net::ERR_ABORTED 404 (Not Found)
Background:
I'm creating a basic image editing site using django, html/css, and injecting JS to apply some filters to images. Previously I was able to make changes and they were reflected in the page, but now I can even delete my css file and it still uses an older version.
Things I've tried:
Gone into settings cleared browser cache
Disabled caching in developer mode
appended the version of css file ?v1.1 to force a rest (caused the 404 error from above)
Run collectstatic in terminal
Cleared cache opened site in private window
Watched several youtube vids on setting up static file dir and I think its correct. At some point in time my css was loading and updating as I made changes.
Directory Layout
These are my settings
Settings.py
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Image_API',
'rest_framework',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Image_API.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, '../static'),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), '../static')
Urls.py File
from django.contrib import admin
from django.urls import path
from Image_API import views
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('',views.upload2, name='upload'),
path('upload/', views.upload2, name='upload'),
path('other/', views.other),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root =settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
How my HMTL Files refrence css
I have load static at the top of the page and have my link to the css in the header tag.
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static '/css/style.css' %}">
It looks like the problem might be coming from your STATIC_URL setting and or STATIC_ROOT. Try changing it to:
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
You might also want to check that your urls.py file is setup correctly:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Restart your server after making these changes just to be sure.
ps: collect static is run during deployment
You might have overlooked and updated CSS in /staticfiles/css/
Instead try updating it in /media/css.
staticfiles directory is auto-generated when you run python manage.py collectstatic.
You can try deleting staticfiles directory and run python manage.py collectstatic and see if it fixes the issue.

Django 2.2 Not Serving Static Files

I am currently working through some tutorials to enhance my knowledge of Django. In doing so, I decided to use to most recent version of Django. I have been able to overcome most of the divergences between my code and that of the tutorial except for one - static files are not being served. Now, I am not fully sure that the difference is strictly due to the Django version. Here is what is going on.
I have the following project structure:
settings.py
STATIC_URL = '/static/'
STATIC_FILES = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "staticfiles", "static")
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
What is interesting is that with this configuration, the project is able to find templates successfully. However, as mentioned above, it cannot find the static files. Why is that?
Also, this tutorial sets up an unusual configuration in that the static and templates directories are located inside the main app's directory, whereas I typically have them one level higher, i.e., in the project root's directory. Could this be a part of the problem? What in the settings of this particular project makes Django look for files one directory lower? The settings seem the same as those of other project I had done. However, those project contained the static and templates directories in the project's root directory.
Any help and clarification is appreciated.
Edit:
urls.py
from django.contrib import admin
from django.urls import path
from .views import home
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home')
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
try replacing this:
STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "staticfiles", "static")
with
STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "static")
Also provide the status of files (like 404 messages)
STATIC_FILES doesn't mean anything to Django, as far as I know, although maybe you are using it for another purpose.
The way you had STATIC_ROOT defined it was pointing to a non-existent directory.
There is a good reference in StackOverflow here
To serve static files you need to add the following configuration in urls.py as:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Next, I believe it is a good practice to put static and templates within their own apps, this is useful if you want to make that app plug-able any near future.
Or it is also a good practice to gather all static files in project level directory and add the following in settings to identify it.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
edit: I just see the updated question. Try adding this:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home')
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
This says, as long as we are in debug mode serve the static files.
try this:
STATIC_ROOT = os.path.join (BASE_DIR, "taskbuster", "static")
I was able to solve the issue by changing the settings to the following:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "static")
Furthermore, it was helpful to read the following documentation when trying to understand how to fix it
https://docs.djangoproject.com/en/2.2/ref/settings/#std:setting-STATICFILES_FINDERS
Particularly, this explained clearly what Django did:
The default will find files stored in the STATICFILES_DIRS setting
(using django.contrib.staticfiles.finders.FileSystemFinder) and in a
static subdirectory of each app (using
django.contrib.staticfiles.finders.AppDirectoriesFinder). If multiple
files with the same name are present, the first file that is found
will be used.

Django Class-based View and URL configuration

I am trying to learn Django and I am stuck with Class-based views and URLconf. From what I understand I should see my test.html at localhost/app1/test1/test/test.html, but I get an error page not found. I am not sure what I am doing wrong.
#~/project_folder/mysite/ulrs.py
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/test1/', include("app1.urls")),
]
#~/project_folder/app1/urls.py
urlpatterns = [
path('test/', TemplateView.as_view(template_name="test.html"), name="home"),
]
#~/project_folder/static/templates
test.html
#~/project_folder/mysite/settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'static/templates'),
],
'APP_DIRS': True,
...
}
STATIC_URL = os.path.join(BASE_DIR, 'static/')
Django html-templates are not supposed to be treated as static files and regular path for them is like "app/templates/app" (examine tutorial and demo-projects)
template file names are not exposed to the end-user and do not partake in url path, so
this particular setup
path('app1/test1/', include("app1.urls")),
path('test/', TemplateView.as_view(template_name="test.html"), name="home"),
actually means: for rendering response on url app1/test1/test/ request use test.html template. If you rename template filename to "whatever-foo-bar-my-template.html" url will not change.

Django 1.10 404.html template not found

As far as I have seen in the Django documentation, to show a custom 404 page all you have to do is put a 404.html in the root templates directory.
So my project structure is:
django_project
|_ config
| |_ settings.py
| |_ urls.py
|
|_ templates
|_ base.html
|_ index.html
|_ 404.html
In settings.py I have the following settings for the templates:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["templates", ]
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'contact.views.contact_info',
],
},
},
]
for the 'DIRS' parameter I also used os.path.join(BASE_DIR, "templates"). This had the exact same outcome.
I also used
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, "templates"),
)
This lead to a deprecation warning.
In urls.py I also did not really do anything special:
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name="index.html"), name="index"),
url(r'^admin/', admin.site.urls),
]
Template inheritance is working perfectly in other apps, so the templates directory is found.
In settings: DEBUG=False
When I enter a wrong url I get the Django default 'NOT FOUND' page.
What am I missing here?
you need override 'handler404' variable, add this to urls.py
from django.conf.urls import handler404
handler404 = 'your_app.views.404'
https://docs.djangoproject.com/en/1.10/topics/http/views/#customizing-error-views
I guess you have to specify route for your 404.html template, or use from django shortcuts 'get_object_or_404' to handle error 404.

Django unable to load JS and CSS files as static resources

I have a html file called base.html inside a folder called html. There are two directories at the same level as html - js and css which contain static resources. The base.html refers those static resources through relative paths, like
<script type="text/javascript" src="../js/debounce.js"></script>
<link rel="stylesheet" href="../css/base.css">
It works as expected. Now I copied the entire directory structure to my django project. This is how the root folder ecom looks like:
The customviews directory contains the html, js and css directories, as well as a myview.py file, which is refered to in the urls.py file within the ecom subdirectory as:
from customviews.myview import *
urlpatterns = [url(r'^admin/', admin.site.urls),
url(r'^time/$', current_datetime),
url(r'^base/', base)]
The base method in myviews.py simply runs as follows:
def base(request):
return render_to_response("base.html")
And the relevant part of settings.py looks like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'DIRS': [os.path.join(dirfunc(dirfunc(__file__)), 'templates').replace('\\', '/'),
os.path.join(dirfunc(dirfunc(__file__)), 'customviews/html').replace('\\', '/'),
os.path.join(dirfunc(dirfunc(__file__)), 'customviews/js').replace('\\', '/'),
os.path.join(dirfunc(dirfunc(__file__)), 'customviews/css').replace('\\', '/')],
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
When I fire up the server and load base, only the basic html is rendered, the css and js are missing. How do I load both?
You don't need to be including the static resource folders in your template dirs. What you do need to do is set your STATICFILES_DIRS under settings and include a static tag in your templates are calling those resources.

Categories

Resources