[Django]-A simple example of Django and CSS

42πŸ‘

βœ…

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:

$ django-admin.py startproject myproject
$ cd myproject
myproject$ python manage.py startapp myapp
myproject$ mkdir myapp/static
myproject$ cd myapp/static
myproject/myapp/static$ nano style.css

In your templates:

<link rel="stylesheet" href="{{ STATIC_URL }}style.css" />

Make sure you add myapp to the INSTALLED_APPS list in settings.py. Now when you use the built-in development server, your style sheet will be rendered correctly.

Django searches for a static directory inside installed applications by default, and with current versions of django, static files are enabled by default.


The Django example has the path my_app/static/my_app/myimage.jpg which
is a little confusing if your app and project have the same name.

This is recommended because when you run collectstatic to gather all your static files, files with the same name will be overwritten. If you have a file called myimage.jpg in 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 your STATIC_ROOT directory.

A simple example to illustrate the point. If you have a django project with two apps, like this:

.
β”œβ”€β”€ assets
β”œβ”€β”€ manage.py
β”œβ”€β”€ myapp
β”‚Β Β  β”œβ”€β”€ __init__.py
β”‚Β Β  β”œβ”€β”€ models.py
β”‚Β Β  β”œβ”€β”€ static
β”‚Β Β  β”‚Β Β  └── myapp
β”‚Β Β  β”‚Β Β      └── test.txt
β”‚Β Β  β”œβ”€β”€ tests.py
β”‚Β Β  └── views.py
β”œβ”€β”€ myproj
β”‚Β Β  β”œβ”€β”€ __init__.py
β”‚Β Β  β”œβ”€β”€ __init__.pyc
β”‚Β Β  β”œβ”€β”€ settings.py
β”‚Β Β  β”œβ”€β”€ settings.pyc
β”‚Β Β  β”œβ”€β”€ urls.py
β”‚Β Β  └── wsgi.py
└── otherapp
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ models.py
    β”œβ”€β”€ static
    β”‚Β Β  └── otherapp
    β”‚Β Β      └── test.txt
    β”œβ”€β”€ tests.py
    └── views.py

assets is your STATIC_ROOT. Now when you run collectstatic:

.
β”œβ”€β”€ assets
β”‚Β Β  β”œβ”€β”€ myapp
β”‚Β Β  β”‚Β Β  └── test.txt
β”‚Β Β  └── otherapp
β”‚Β Β      └── test.txt
β”œβ”€β”€ manage.py
β”œβ”€β”€ myapp
β”‚Β Β  β”œβ”€β”€ __init__.py
β”‚Β Β  β”œβ”€β”€ __init__.pyc
β”‚Β Β  β”œβ”€β”€ models.py
β”‚Β Β  β”œβ”€β”€ static
β”‚Β Β  β”‚Β Β  └── myapp
β”‚Β Β  β”‚Β Β      └── test.txt
β”‚Β Β  β”œβ”€β”€ tests.py
β”‚Β Β  └── views.py
β”œβ”€β”€ myproj
β”‚Β Β  β”œβ”€β”€ __init__.py
β”‚Β Β  β”œβ”€β”€ __init__.pyc
β”‚Β Β  β”œβ”€β”€ settings.py
β”‚Β Β  β”œβ”€β”€ settings.pyc
β”‚Β Β  β”œβ”€β”€ urls.py
β”‚Β Β  └── wsgi.py
└── otherapp
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ __init__.pyc
    β”œβ”€β”€ models.py
    β”œβ”€β”€ static
    β”‚Β Β  └── otherapp
    β”‚Β Β      └── test.txt
    β”œβ”€β”€ tests.py
    └── views.py

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

πŸ‘€Burhan Khalid

14πŸ‘

The recommended approach has changed again (from at least Django 1.5 I think).

At the top of your template put:

{% load staticfiles %}

Then, using the same directory structure (myapp/static/myapp/style.css):

<link rel="stylesheet" href="{% static 'myapp/style.css' %}" />

Source

πŸ‘€Chris

7πŸ‘

For the examples you pointed at to work, your static files need to be in a location accessible to Django’s built-in staticfiles app.

There are a couple steps to make this happen:

First, within your project directory (ie beside your manage.py file), you’ll need to create a directory to hold your static files. Call it β€œstatic_files”.

Next, you’ll need to let Django know to look in that directory, by specifying it in the list of STATICFILES_DIRS within your settings.py file.

Something like this:

STATICFILES_DIRS = [
    '/full/path/to/your/project/static_files/',
]

Within that static_files directory, you can create whatever structure you want, so that is where your css and js directories could go.

After that, you should be able to use the {{ STATIC_URL }} tag in your templates to get access to the base URL of your static files.

So, say, for example, you create project/static_files/css/base.css, you would use it in your template like so:

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}/css/base.css" />

Hope that helps!

Edit

With the default settings for STATICFILES_FINDERS, Django should automatically serve up any files from directories listed in your STATICFILES_DIRS β€” see the docs for details.

If this doesn’t work, some things to check:

  • Have you edited your STATICFILES_FINDERS setting to something other than the default?
  • Is django.contrib.staticfiles in your list of INSTALLED_APPS in settings.py?
  • Are you using Django’s built-in server (python manage.py runserver)?
  • Do you have DEBUG = True in your settings.py? If not, you’ll need to either set it to True or use the insecure option (python manage.py runserver --insecure). When going to production, check out the collectstatic command.
πŸ‘€Gabriel Grant

4πŸ‘

finally i got after many days here is how should be done
1> you need your static file in your app along with in your project
2> here is setting.py

   if DEBUG:
   STATIC_ROOT = "/PycharmProjects/don/admin/shopping/static/css"

    STATICFILES_DIRS =(
     #os.path.join(os.path.dirname(BASE_DIR),"static","static"),
     os.path.join(BASE_DIR, "static"),
    )

3>views.py

        from django.views.generic import TemplateView
        class HomeView(TemplateView):
               template_name = 'index.html'

4> template file

       {% load staticfiles %}
        <link rel="stylesheet" href="{% static 'css/style.css' %}">

5> urls.py

            from shopping.views import HomeView 
             from django.conf import settings
             from django.conf.urls.static import static
           urlpatterns = [
            url(r'^admin/', admin.site.urls),
             url(r'^$', HomeView.as_view())
          ]
        if settings.DEBUG:
       urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)

6>     python manage.py collectstatic  

have fun :)
πŸ‘€Roshik Dahal

3πŸ‘

The handling of static files has changed significantly (for the better) in Django 1.3. In particular is the flexible difference between static files (think code required CSS/JS/images) and media files (think images uploaded by users in the use of you application). The staticfiles app handles what you are asking for.

Put django.contrib.staticfiles in your settings.py INSTALLED_APPS. Then create a static directory inside your app directory – so project/app/static/. Within that static directory organize your support files as you like (css/, js/, images/, icons/, etc). staticfiles by default will look in the static/ directory for every app listed in INSTALLED_APPS. Not just your own, but all the Django apps and third-party apps. (sidenote: the Admin in Django 1.4 moves to this paradigm while in 1.3 it still uses the ADMIN_MEDIA_PREFIX).

The staticfiles app knows about all those static/ directories in all the apps but it needs to collect all that content in order to serve it. In development, when using manage.py runserver it is handled for you. Django will run your site and automatically deliver all the static content from all the static sources. (Sources, as mentioned in another answer, are set in the STATICFILES_FINDERS setting.) When not using runserver, use manage.py collectstatic to gather all the static files into the folder defined in STATIC_ROOT. Keep this directory empty. It is a collection destination. Of course your web server will need to be configured to serve this directory.

Now there is one more piece – the view. This is where the STATIC_URL comes into play. When referring to static files in your templates, the easiest way is to use {{ STATIC_URL }}. Django by default makes that variable available to any view using the RequestContext. Do something like this – <link rel="stylesheet" href="{{ STATIC_URL }}/css/main.css" />.

For more information and more ways to refer to STATIC_URL in your templates, check out this answer to a similar question.

πŸ‘€JCotton

0πŸ‘

Here’s a hacky workaround for views.py when debug in settings.py is False

def my_style(request):
    my_file = open('path to arbitrary css file', 'r')
    response = HttpResponse(content=my_file.read())
    response['Content-Type'] = 'text/css'
    return response

and here’s the urls.py

urlpatterns = [
    path('hello', views.hello_world, name='hello_world'),
    path('static/my_style/', views.my_style, name='my_style'),
]

And here’s the insert for the html file

<link rel="stylesheet" type="text/css" href="static/my_style">

Though this is clearly not how Django was meant to be used, and I’m guessing this could have some security implications.

0πŸ‘

You can add CSS in Django Templates. *My answer explains how to load CSS and JavaScript files in Django.

For example, there is hello.css in static/my_app1/css/ and there is index.html in templates/ as shown below:

django-project
 |-core
 |  β””-settings.py
 |-my_app1
 |-my_app2
 |-static
 |  β””-my_app1
 |     β””-js
 |        β””-hello.css # Here
 β””-templates
    β””-index.html # Here

Then, set BASE_DIR / 'templates' to DIRS in TEMPLATES and set BASE_DIR / 'static/' in STATICFILES_DIRS in settings.py as shown below so that Django can recognize templates and static folders just under django-project. *My answer explains how to set Django Templates and I recommand to set whitenoise following my answer to disable your browser to cache the static files of Django:

# "settings.py"

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR / 'templates' # Here
        ],
        ...
    },
]

...

STATIC_URL = 'static/'
STATIC_ROOT = 'staticfiles/'
STATICFILES_DIRS = [
    BASE_DIR / 'static/' # Here
]

Lastly, add <script ...></script> to index.html as shown below:

{# "index.html" #}

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="{% static 'my_app1/css/hello.css' %}">
</head>

<body>
</body>
</html>

Leave a comment