Django CSS & Static Media Not Loading - django

So I've been hitting my head against the wall on this for the last hour and can't seem to figure out why none of the static media (CSS, Images, JS etc) when my template is rendered.
Could someone please help me find out why adjustments I need to make? Below are snippets from Settings.py, Index.html and stylesheet please let me know if more is needed.
My static files are located in the following directory:
/djangoproject/website/static
Settings.py - Located /djangoproject/djangoprojectname/
STATIC_ROOT = os.path.normpath(os.path.join(PROJECT_ROOT,
"/static/"))
STATIC_URL = '../website/static/'
Here's a snippet from my index.html that is supposed to be calling the css style sheet with {{ STATIC_URL }}
Index.html - Location /djangoproject/website/templates/
<link rel="stylesheet" href="{{ STATIC_URL }}css/style.css">
Location of CSS StyleSheet
style.css - Location /djangoproject/website/static/css/

From the Django docs:
If {{ STATIC_URL }} isn't working in your template, you're probably
not using RequestContext when rendering the template.
As a brief refresher, context processors add variables into the
contexts of every template. However, context processors require that
you use RequestContext when rendering templates. This happens
automatically if you're using a generic view, but in views written by
hand you'll need to explicitly use RequestContext To see how that
works, and to read more details, check out Subclassing Context:RequestContext.

It seems to me that you are setting STATIC_URL to a path, when it should be set to, well, a URL. You need to set this to the web address of the folder that contains your css files, for example:
STATIC_URL = 'http://mydomain.com/static_files/'
Try to find your CSS file online by typing the address you expect it to be into your browser. Once you find the CSS file this way, just copy the root URL that got you there.

Related

Django : Page Not Found when trying to access static files

I know there are already several threads on the topic. I've been through most of them (especially all the troubleshooting listed in this one) but I can't figure out my issue.
I am trying to use a Bootstrap template in my Django project, and I'd like to simply start by accessing the files in the /static/ directory. My project directory looks like this :
Whenever I try to load the page http://localhost:8000/static/theme/assets/css/style.css it returns a Page not found error (and obviously no CSS/JS content appears on my index).
Here are my settings:
I have debug = True
ÌNSTALLED_APPS contains django.contrib.staticfiles
settings.py looks like this :
STATIC_URL = "/static/"
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),)
But I still can't access anything from the /static/ directory.
I tried to access the CSS and JS files in base.html this way :
{% load static %}
...
<link href="{% static 'theme/assets/css/style.css' %}" rel="stylesheet">
I really have no clue how I could solve this.
Thanks in advance for your help !
Is base.html properly bound to a URL and to a view function via a URL dispatcher ? Can you access that file from your browser ?
If yes, try to substitute this line
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),)
with this one
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)

How can I apply bootstrap to my whole django project?

I've been looking at a few guides on applying bootsrap to django, and I am as far as having a static file in the root of my site, containing the css and js files within bootstrap, but when it comes to linking the files I am having an issue.
So I am trying to link the stylesheet inside of my base.html file but am not sure how to format it as for some reason using {% %} inside of the href field is being interpreted as part of the directory. In one of the videos I have watched he links it like thisBut I'm not really sure how to interpret this as trying to apply it to my own like so
href = "{% static 'artForAll/css/bootstrap.css' %}"
With the file structure for reference:
\AFA\src\artForAll\static\artForAll\css
I am given an error about a non existent file as it is taking the {%%} as part of the directory
My settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,"static"),
]
File structure(blue highlighted file is where BASE_DIR leads:

Is it possible to hardcode CSS link in django?

I have an django project and want to hardcode a link to CSS (I do not want to use STATIC_FILES...etc). The reason is because I want to be able to click index.html and it will work on browser (including getting the css file).
I put both index.html and index.css in the same directory and added this line in index.html:
<link rel="stylesheet" type="text/css" href="./index.css"/>
When I double-click index.html, it imports index.css perfectly.
However, when I load it with the django development server and open via browser, it does not import the index.css.
What should be done so that index.html takes the index.css?
The answer by Christopher Schäpers works nicely, I'd like to extend her answer by showing how you may actually do what she suggests.
Let's say you have
<link rel="stylesheet" type="text/css" href="/index.css"/>
which means the browser is requesting to localhost:8000/index.css, so in your root urls.py file, you add something like this
from django.urls import path
from django.conf import settings
from django.http import HttpResponse
def css_path(request): # This is basically a "view"
path = settings.BASE_DIR / 'index.css' # For earlier Django version: os.path.join(settings.BASE_DIR, 'index.css')
with open(path, 'rb') as f:
content = f.read()
return HttpResponse(content, content_type='text/css')
urlpatterns = [
# ... (your other url patterns)
path('index.css', css_path)
]
NOTE: Remember to set the content_type keyword argument correctly base on what you are serving (Example: application/javascript for .js, image/png for .png, .etc).
That's because the browser uses a directory based approach.
Say your template directory looks like this:
/home/yura/project/templates/
→ index.html
→ index.css
When opening index.html with your browser it plainly looks for index.css in the same directory, thus for /home/yura/project/templates/index.css.
Now when you run the development server it's not directory based anymore. There's the urls.py file that specifies where each path leads to.
You probably have a route / that leads to index.html even though index.html isn't called nothing. You could also add a route /blog/ that may lead to blog_home.html even though the file is called blog_home.html.
Every url that enters django is routed through the urls.py file.
This is one of django's core concepts. URLs should be user-typable and readable without cruft as .php, .html and so on that comes from directory based approaches like PHP or CGI.
Since you haven't defined a route called /index.css thus index.css isn't found.
If the thing you are doing is a one-off your best bet would be to just add a route to /index.css that delivers index.css.
Otherwise there is no way of doing this, since django isn't directory based, as pointed out above.
You might then want to think about why exactly you want to be able to open the raw html file directly in the browser too, since it makes the django templating language entirely useless for you, thus you can't do anything variable, loop and logic related and are stuck with basic html where you, instead of the django-dev server could just as well use a simple http-server instead.

Cannot get images to display in Django(1.3) project

I'm making a simple Django project but I cannot get any images to display in my pages.
Django documentation at https://docs.djangoproject.com/en/1.3/howto/static-files/#basic-usage states
Basic usage Put your static files somewhere that staticfiles will find
them.
By default, this means within static/ subdirectories of apps in your
INSTALLED_APPS.
Your project will probably also have static assets that aren’t tied to
a particular app. The STATICFILES_DIRS setting is a tuple of
filesystem directories to check when loading static files. It’s a
search path that is by default empty. See the STATICFILES_DIRS docs
how to extend this list of additional paths.
Additionally, see the documentation for the STATICFILES_FINDERS
setting for details on how staticfiles finds your files.
Make sure that django.contrib.staticfiles is included in your
INSTALLED_APPS.
For local development, if you are using runserver or adding
staticfiles_urlpatterns to your URLconf, you’re done with the setup –
your static files will automatically be served at the default (for
newly created projects) STATIC_URL of /static/.
You’ll probably need to refer to these files in your templates. The
easiest method is to use the included context processor which allows
template code like:
See Referring to
static files in templates for more details, including an alternate
method using a template tag.
So I did this in settings.py:
STATICFILES_DIRS = (
'/home/abc/django/project1/media/',
)
and enabled 'django.contrib.staticfiles',
In media, I have a folder img, which has various jpg files.
In my template, I have this as one of the lines:
<img src="{{STATIC_URL}}img/{{var}}.jpg">
When I'm passing var to this template via my view.
The HTML page seems to render this tag as "<img src="img/abc.jpg"> where var="abc".
But my browser refuses to display the image. What have I done wrong?
Did you see ths part in the documentation:
If {{ STATIC_URL }} isn't working in your template, you're probably not using RequestContext when rendering the template.
Do you also use RequestContext in your view to render the template?
Here is an alternative approach:
settings.py:
import os
PROJECT_DIR = os.path.dirname(__file__) + '/../'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'media/')
STATIC_URL = '/media/'
In your template:
{% load staticfiles %}
<img src="{% static img/foo.jpg %}" />
If you need to pass a variable, use the prefix method:
{% load staticfiles %}
<img src="{% get_static_prefix %}img/{{var}}.jpg" />

trouble updating media_root in django settings.py

I'm trying to set up a MEDIA_ROOT however when I set this in my settings.py it doesn't seem to be recognized. For example my settings.py looks like:
...
MEDIA_ROOT = '/static/files/'
...
And in a template (to test this change) - I tried:
Media root: {{ MEDIA_ROOT }}
static url: {{STATIC_URL }}
static url displays fine and i can update and change it and those changes are reflected in the test template. However media root is always an empty string. Is there some additional config required to start using MEDIA_ROOT - can someone point me to documentation if so?
There are two context variables which should be available to you by default (as long as you use a RequestContext instance when rendering your template:
MEDIA_URL -- provided by django.core.context_processors.media
STATIC_URL -- provided by django.code.context_processors.static
Both of those context processors are in the default list, as you can see at https://docs.djangoproject.com/en/1.3/ref/settings/#template-context-processors
MEDIA_ROOT is supposed to be a filesystem path, and is used for loading and saving media on disk. There shouldn't be any reason to use it in a template. IF you really need access to it, it is simple enough to write your own context processor to provide it.
The documentation on the media processor, btw, is at https://docs.djangoproject.com/en/1.3/ref/templates/api/#django-core-context-processors-media