I’m new to Django, and am trying to set up a really simple Django app.
Now, I’m up to chapter 5 in the Django online book : http://www.djangobook.com/en/2.0/chapter05/
All I want to do now, before I start trying databases, is to add in some simple CS and J to the app as is.
So the question is, how do I do this? I only have one app, and I only want a main.css in a css folder, and a main.js in a js folder.
I checked out the https://docs.djangoproject.com/en/1.3/howto/static-files/#staticfiles-in-templates page, but after reading and reading, there didn’t seem to be a whole lot to work with in terms of examples.
How do I import the stylesheets/css (is there a helper like CakePHP?), where do I put the CSS and JS files, and do I need to configure the static thingy?
UPDATE: the link : Render CSS in Django does not help much. Mainly in that it didn’t work for me, but also I especially don’t like the “if debug” part. What happens when I move to prod? Why would I have my media folder defined differently for prod and local dev anyway? Shouldn’t it be relative, or even in the same spot?
If you follow django’s guidelines, you can simplify your life greatly.
In your sample code, inside your application directory, create a folder called static. Inside this folder, place your css files.
Example:
In your templates:
<link rel="stylesheet" href="{{ STATIC_URL }}style.css" />Make sure you add
myappto theINSTALLED_APPSlist insettings.py. Now when you use the built-in development server, your style sheet will be rendered correctly.Django searches for a
staticdirectory inside installed applications by default, and with current versions of django, static files are enabled by default.This is recommended because when you run
collectstaticto gather all your static files, files with the same name will be overwritten. If you have a file calledmyimage.jpgin another application, it will be overwritten. Giving the application name inside the static directory will prevent this, because the exact directory structure will be replicated inside yourSTATIC_ROOTdirectory.A simple example to illustrate the point. If you have a django project with two apps, like this:
assetsis yourSTATIC_ROOT. Now when you runcollectstatic:You see it is creating the directories as well. In your templates you would now refer to each file with its “namespace” of the app:
{{ STATIC_URL }}/myapp/test.txt