Home > Software engineering >  Django 4 Static files : what's the best practice
Django 4 Static files : what's the best practice

Time:12-21

I'm currently building a project on Django 4.0 and I want to do the static files management the best and the cleaner for this version.

Currently I have this project tree :

enter image description here

And here is my settings file :

BASE_DIR = Path(__file__).resolve().parent.parent.parent
(...)
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

When I try to find some videos about the subject, no one is using the same structure and setup for static files. In this sample, I have a 404 error on my dist/css/output.css file.

In my HTML template I try to call it that way :

<link href='{% static "css/dist/output.css" %}' type="text/css" rel="stylesheet">

Could someone please copy/past me an easy static setup for handling static properly ? Or at least, help me to understand why it doesn't work and what I should do ?

Moreover, I put my static directory outside my main app, but some are putting it in. So I don't know what's best...

Thanks :)

CodePudding user response:

The best way to configure your static files in django 4 is to use pathlib instead of importing an extra module eg. os
and problem is that you don't have css folder inside your static folder so instead of this

STATICFILES_DIRS = [
    BASE_DIR / "static",
]

<link href='{% static "css/dist/output.css" %}' type="text/css" rel="stylesheet">

you have to put this

<link href='{% static "dist/output.css" %}' type="text/css" rel="stylesheet">

or you can create css folder and add dist folder inside it

  • Related