Django Static Files(CSS) don't link with template - css

Just as the title says, static files somehow are not loading up in my template. I've tried working on it and looking at similar StackOverflow questions but I can't find a solution. I tried debugging it using browser's dev tools.
I tried opening the CSS file from there but it just leads me to this error. This leads me to the conclusion that Django doesn't seem to find base.css inside the static folder. I've already done manage.py collectstatic so there shouldn't be a problem. Thanks!
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/static/static/base.css
'static\base.css' could not be found
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
settings.py
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
template
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}">
edit: reverted back {% static 'static/base.css' %} to {% static 'css/base.css' %}

Firstly, you have to correct the settings.py :
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
Then, lets say, you stored your css file in static/base.css
Now, write, {% static 'base.css' %} because django by-default look up for your static files in your app so you dont have to include static path.

Related

How to use bootstrap styling in django project

I have downloaded bootstrap files (css, js) and put in the static folder of my project and made changes in header section of index.html as shown in the below code. But still django can't locate bootstrap.min.css as shown in the error
"GET /static/css/bootstrap.min.css HTTP/1.1" 404 1687
Project Structure
Project
|---Project
|---static
|---css
|---js
|---templates
|---index.html
|---manage.py
index.html
<head>
{% load staticfiles %}
<link rel='stylesheet' href="{% static 'css/bootstrap.min.css' %}" type='text/css' />
</head>
I followed tutorials and read documentation But could not locate the problem can anybody help, thanks in advance.
I'm not seeing anything wrong with your HTML or Project Structure.
Did you set STATICFILES_DIRS in your settings.py?
settings.py
# Add this at the end of your code if it isn't there already
STATICFILES_DIRS = [
os.path.join("Project", "static"),
]
In your settings.py, should have BASE_DIR. It should look like this:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
And add STATICFILES_DIRS at the end of your settings.py
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

django 1.8 admin site css issue while css file loads fine

django 1.8 on a production server:
When loading the admin page, it shows the content without rendering the css, similar to the site shown here.
There are no errors in chrome developer tools. These 2 css files load fine:
<link href="/static/admin/css/base.7cdd754721f8.css" rel="stylesheet" type="text/css"/>
<link href="/static/admin/css/dashboard.4898e2e9983d.css" rel="stylesheet" type="text/css"/>
Still the admin interface appears unstyled.
Relevant settings:
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticroot')
STATIC_URL = '/static/'
ABS_TEMPLATES_PATH = PROJECT_ROOT + '/templates'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'project_docs/site'),
)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
Any suggestions?
This was caused by wrong css files being loaded.
The mkdocs package (http://www.mkdocs.org/) also has a file called "base.css".
Static file collection brought them erroneously to the same place, overwriting the django admin base.css file.
So django admin was loading the mkdocs theme...
Corrected the static file collection so these files do not overwrite each other and the issue is solved.

Django static files - error 404 on access attempt

I'm following the gettingstartedwithdjango.com tutorials but with newer versions of code. I'm on the second tutorial and I'm near the end but I'm unable to successfully style my site with CSS due to 404 errors serving static files content. I'm not exactly clear on why.
I'm running a Vagrant VM atop Windows 7 for development, /vagrant (in the VM) is mapped to C:/VAGRANT (in Win7). I created C:/VAGRANT/PROJECTS to contain all of my projects. I created a virtualenv for my project which sits in /home/vagrant/blog-venv (in the VM), the contents for that project from a code perspective sit in C:/VAGRANT/PROJECTS/microblog.
DIRECTORY STRUCTURE
PROJECTS
static # subdirs not auto-created yet as functionality not yet working
uploads # subdirs not auto-created yet as functionality not yet working
microblog
manage.py <file>
assets
css
fonts
js
microblog
settings
templates
_layouts
blog
migrations
templates
blog
Based on the above directory structure, here are the relevant files and their contents:
/microblog/microblog/settings/__init__.py
from .base import *
try:
from .local import *
except ImportError:
pass
/microblog/microblog/settings/base.py
DEBUG = False
here = lambda * x: os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
PROJECT_ROOT = here("..")
root = lambda * x: os.path.join(os.path.abspath(PROJECT_ROOT), *x)
TEMPLATES = [
{
'DIRS': [
root("templates")
},
]
MEDIA_ROOT = root("..", "..", "uploads")
MEDIA_URL = ''
STATIC_ROOT = root("..", "..", "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
root("..", "assets"),
]
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
ALLOWED_HOSTS = ['*']
DJANGO_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
THIRD_PARTY_APPS = []
LOCAL_APPS = [
'blog',
]
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
/microblog/microblog/settings/local.py
DEBUG = True
/microblog/microblog/urls.py
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
import blog.urls
from . import views, settings
admin.autodiscover()
urlpatterns = [
url(r'^$', views.HomepageView.as_view(), name="home"),
url(r'^blog/', include(blog.urls, namespace="blog")),
url(r'^admin/', admin.site.urls),
# url(r'^static/(.*)$', 'django.views.static.serve', {'document_root': settings.base.STATIC_ROOT}),
]# + static(settings.base.STATIC_URL, document_root=settings.base.STATIC_ROOT)
/microblog/microblog/views.py
from django.views.generic import TemplateView
class HomepageView(TemplateView):
template_name = "index.html"
/microblog/blog/views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post
class PublishedPostsMixin(object):
def get_queryset(self):
queryset = super(PublishedPostsMixin, self).get_queryset()
return queryset.filter(published=True)
class PostDetailView(PublishedPostsMixin, DetailView):
model = Post
/microblog/microblog/templates/_layouts/base.html
<!doctype html>
<html>
<head>
<title>{% block page_title %}{% endblock %}Microblog</title>
<link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Welcome to my site!</h1>
{% block page_content %}{% endblock %}
</div>
</body>
</html>
/microblog/microblog/templates/index.html
{% extends "_layouts/base.html" %}
{% block page_content %}
<a href="{% url 'blog:list' %}" class='btn'>Read my blog</a>
{% endblock %}
THE RUNSERVER ERROR I'M SEEING IS:
Performing system checks...
System check identified no issues (0 silenced).
December 23, 2015 - 11:13:14
Django version 1.9, using settings 'microblog.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
[23/Dec/2015 11:13:20] "GET / HTTP/1.1" 200 391
Not Found: /css/bootstrap.min.css
[23/Dec/2015 11:13:20] "GET /css/bootstrap.min.css HTTP/1.1" 404 2190
ATTEMPT AT PROBLEM DIAGNOSIS
Taking the 'Not Found' message from above, the path /css/bootstrap.min.css rather than /static/css/bootstrap.min.css has lead me to believe the problem is manifesting itself in the /microblog/microblog/templates/_layouts/base.html file here:
<link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap.min.css">
It appears that {{ STATIC_URL }} is not being interpreted to it's it set value of '/static/' and therefore the lookup path is /css/bootstrap.min.css rather than the expected /static/css/bootstrap.min.css. Yes, I have validated that the expected path and file does exist on the actual file system. Accordingly, when the page renders, it's just your standard HTML output without the CSS styling that I'm expecting. In the /microblog/microblog/templates/index.html file, the class="btn" is not working/rendering properly either.
I have read that this might have to do with the values of DEBUG and/or ALLOWED_HOSTS and of course I suspect my PATHS.
Let's deal with the paths first. It could be that best-practices dictate that I should adjust my current paths somewhat, please advise (lack of experience here), but for now I'm just following what I was told to do on the tutorial website. In that vein and since I'm not using hard-coded paths, I have confirmed the post-code-interpretation (base.py) of each of my paths, as well as the actual existence of each of these folders in my file system (see the DIRECTORY STRUCTURE block near the top of this post) as follows:
here() = /vagrant/PROJECTS/microblog/microblog/settings
PROJECT_ROOT = /vagrant/PROJECTS/microblog/microblog
root() = /vagrant/PROJECTS/microblog/microblog
TEMPLATES = [{'DIRS': = /vagrant/PROJECTS/microblog/microblog/templates }]
MEDIA_ROOT = /vagrant/PROJECTS/uploads
MEDIA_URL = ''
STATIC_ROOT = /vagrant/PROJECTS/static
STATIC_URL = '/static/'
STATICFILES_DIRS = [ /vagrant/PROJECTS/microblog/assets ]
With regards to DEBUG needing to be set to 'True', this is the case in my local.py file, which is imported when I run Django locally but not imported when I push code to production (local.py is excluded from production sync via .gitignore).
With regards to ALLOWED_HOSTS you'll see I currently have a value of '*' which may or may not be appropriate. I don't know, lack of experience.
I've noticed that running python manage.py collectstatic collects 0 files but I'm unsure why.
You'll notice that my /microblog/microblog/urls.py has some lines commented out of it, I've tried various things here to try to resolve the issue.
One further observation. The admin side of my project has the default styling typical of the Django Admin interface but this only became true when I enabled the STATICFILES_FINDERS called django.contrib.staticfiles.finders.AppDirectoriesFinder. I believe that's because this causes Django to go look where the files are for the admin app. Since these haven't been synced to the STATIC_ROOT location (because python manage.py collectstatic is failing), I'm assuming it's looking in the location where my VENV makes these files available (/home/vagrant/blog-venv/lib/python2.7/site-packages/django/contrib/admin). Can anyone confirm this? As for the front-end side of the project, that piece is obviously still having trouble.
I'm relatively new to Django and I'm very stuck on this problem. Essentially this boils down to getting static files working for my site as a whole and without that I'm kind of dead in the water as I will need static files functionality for other aspects of my project too. I don't know if there is a better way I should be troubleshooting or debugging. I sort of expect that I'd get a browser error page (since DEBUG=True) that would help me further narrow down the problem but I'm not getting this despite my DEBUG setting. I also don't know if there is a way to python manage.py runserver with parameters which would produce more debug output as to why I'm getting the 404.
Any assistance or advice with this problem as a whole will be greatly appreciated. If any further information is required, please request and I will post an update. Thank you in advance!
This is really the key point to look at:
[23/Dec/2015 11:13:20] "GET /css/bootstrap.min.css HTTP/1.1" 404 2190
The /static prefix is missing from /static/css/bootstrap.min.css.
As the documentation explains, you should include this in your template to use static files:
{% load staticfiles %}
And in modern versions of Django, instead of:
<link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap.min.css">
You should use:
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
This static template tag appeared in Django 1.4, and has been the preferred approach since.

Django MEDIA_URL and MEDIA_ROOT issue with CSS

I'm having a very similar problem to this question but unfortunately none of the solutions seem to be working for me.
Essentially I have the following, really simple directory:
ulogin
- models.py
- tests.py
- views.py
- media
- screen.css
- templates
- utemplate
- index.html
in my settings.py I have the following defined:
MEDIA_ROOT = '../compwebsite/ucode/ulogin/media'
MEDIA_URL = '/media/'
and in index.html I have the following trying to reference screen.css
<html>
<head>
<title>
YAY TITLE
</title>
<link rel="stylesheet" href="{{ MEDIA_URL }}screen.css">
<!--and it more...-->
My urls.py I have the following:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
No matter what I do, I can't get the reference to the screen.css to work. I'm really uncertain of how to fix this based on the other questions here on the site. Thank you so much and let me know if you need more info!
Static files should be placed in the 'static' directory; this is where Django will look. The 'media' directory is meant to hold user-uploaded files, which get copied over to the static directory when the django server runs.
Change your MEDIA_URL references to STATIC_URL
You shoudn't have to use the URLConf to manage static files at all.
As for your Django settings, it's not a good idea to hard code absolute paths in case they are changed (i.e. when pushed to a deployment server).
A better idea is to do something like this:
from os import path
PROJECT_ROOT = path.abspath(path.dirname(path.dirname(__file__)))
MEDIA_ROOT = path.join(PROJECT_ROOT, 'media/')
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
path.join(PROJECT_ROOT, 'static/'),
)
This will ensure that Django is using the correct absolute path regardless of where your project is on your system.
You can also enable the DefaultStoreFinder in STATICFILES_FINDERS although it shouldn't be necessary.

How to serve static files for local development in Django 1.4

I just downloaded the latest Django version (1.4.1), and I can't figure out how to serve css files when developing locally using runserver. I've read the relevant Django docs on static files and many, many questions & answers here... sounds like it's supposed to be more or less automatic, but it's not working for me.
I'm working on the polls app from the tutorial.
404 from the log
[27/Apr/2012 01:04:09] "GET /polls/ HTTP/1.1" 200 210
[27/Apr/2012 01:04:09] "GET /polls/css/styles.css HTTP/1.1" 404 2596
Directory structure
mysite
|-- manage.py
|-- mysite
|-- __init__.py
|-- settings.py
|-- urls.py
|-- wsgi.py
|-- polls
|-- __init__.py
|-- models.py
|-- tests.py
|-- views.py
|-- static
|-- css
|-- styles.css
|-- templates
|-- polls
|-- index.html
index.html
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/styles.css">
settings.py
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
'django.core.context_processors.static',
)
^^^ I didn't have the TEMPLATE_CONTEXT_PROCESSORS variable in settings.py when I started the project and had to add it manually - should I be worried about that?
STATICFILES_DIRS is empty, because the css file is in a directory named static within the polls app, which is where Django looks for it automatically - right?
I also have django.contrib.staticfiles in my INSTALLED_APPS.
urls.py
I saw in the docs that this solution works for local development servers other than runserver - sounds like it shouldn't be necessary otherwise, right? (I currently have it commented out.)
EDIT: I uncommented these lines, but did not see a change - still getting the same 404 on the css file
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
Do I have my directory structure set up wrong? Am I missing necessary settings in settings.py? Any help would be very much appreciated! Thanks!
EDIT:
I took Mark's suggestion and read up on RequestContext. Changing my view from:
return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
to
from django.template import RequestContext
...
return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list}, context_instance=RequestContext(request))
got the /static/ url to register:
[27/Apr/2012 13:56:55] "GET /static/css/styles.css HTTP/1.1" 200 19
This fixes the problem.
In order to use STATIC_URL in the template you need to be sure you are using a RequestContext along with adding 'django.core.context_processors.static' to TEMPLATE_CONTEXT_PROCESSORS. This is done for you if you are using the render shortcut. If you are not using a RequestContext then you can use the {% get_static_prefix %} template tag from the staticfiles template tag library. This is detailed in the docs here: https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#other-helpers
.'
I had the same problem, and evnetually with the same coinfuration as mentioned above this did the trick:
i added in setting.py the path to my static directory in STATICFILES_DIRS:
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR,'static'),
)
when also in settings.py PROJECT_DIR is set to:
PROJECT_DIR=os.path.dirname(os.path.abspath(__file__))
From your 404, looks like you're not including {{ STATIC_URL }} in your template. That's probably the problem. instead of just "css/file", do "{{ STATIC_URL}}css/file"
Without looking too hard, your settings looks fine. If the above doesn't work, try running ./manage.py collectstatic and see if that helps (it moves static files from app directories into a project static directory).
And definitely uncomment those lines in your urls.py!
If you don't have static url patterns, when it goes to request something from /static/, it won't know what to do.
This worked for me under development server:
1. I added "static" folder under my application "myblog" directory.
2. Added "myblog.css" file inside "static" folder.
3. Linked the style sheet to my application's template, code is below.
<link rel="stylesheet" href="{{ STATIC_URL }}myblog.css" type="text/css" media="screen" />
I did not change settings.py or urls.py files in order to fix css, the changes were made are only according to tutorial, so you should have the same.

Resources