Javatpoint Logo
Javatpoint Logo

Django Static Files Handling

In a web application, apart from business logic and data handling, we also need to handle and manage static resources like CSS, JavaScript, images etc.

It is important to manage these resources so that it does not affect our application performance.

Django deals with it very efficiently and provides a convenient manner to use resources.

The django.contrib.staticfiles module helps to manage them.

Django Static (CSS, JavaScript, images) Configuration

1. Include the django.contrib.staticfiles in INSTALLED_APPS.

2. Define STATIC_URL in settings.py file as given below.

3. Load static files in the templates by using the below expression.

4. Store all images, JavaScript, CSS files in a static folder of the application. First create a directory static, store the files inside it.

django static files handling

Our project structure looks like this.

django static files handling 1

Django Image Loading Example

To load an image in a template file, use the code given below.

// index.html

//urls.py

//views.py

Run the server by using python manage.py runserver command.

After that access the template by localhost:8000/index URL, and it will produce the following output to the browser.

django static files handling 2

Django Loading JavaScript

To load JavaScript file, just add the following line of code in index.html file.

// index.html

// script.js

Now, our project structure looks like this:

django static files handling 3

Run the server by using python manage.py runserver command.

After that access the template by localhost:8000/index URL, and it will produce the following output to the browser.

django static files handling 4

Django Loading CSS Example

To, load CSS file, use the following code in index.html file.

After that create a directory CSS and file style.css which contains the following code.

// style.css

Our project structure looks like this:

django static files handling 5

// index.html

Run the server by using python manage.py runserver command.

After that access the template by entering localhost:8000/index URL, and it will produce the following output to the browser.

django static files handling 6

Well, in this topic, we have learned the process of managing static files efficiently.


Next TopicModelForms





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA