Link Static files like CSS, JS and images in django

How to link css, js and images in Django ?

To link the static files i.e. the css, js and images files, first we need to create a folder with the name "static" in the main directory of our project.

>accounts
>funda
>static

Now create your folders like css, js and images inside the static folder.

We have to tell django where we have kept our static files. Open your settings.py file and paste the below code :

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

MEDIA_URL = '/images/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]


Now we have successfully added the static files in our project. Now lets link it in our files. To link the static files, we need to load it at the top of the page and then use it in the page as shown below:

{% load static %}
<html lang="en">
<head>
    <link rel="stylesheet" href="{% static '/css/bootstrap.css' %}">
    <link rel="stylesheet" href="{% static '/css/custom.css' %}">

    <title>
        Funda of Web IT
    </title>
</head>
<body>
    {% include 'accounts/layouts/includes/navbar.html' %}
    {% block content %}

    {% endblock content %}

    <script src="{% static '/js/jquery.js' %}"></script>
    <script src="{% static '/js/bootstap.js' %}"></script>
    <script src="{% static '/js/popper.js' %}"></script>
    
    {% block scripts %}
    
    {% endblock scripts %}
</body>
</html>

As shown above, we can use the static files by using the static in the tags followed by the path inside the static folder.

Note : Always remember to add the {% load static %} on top of the page to use the static files in the current file.
Tags: Funda of web it Django tutorials, Django tutorials, Django tutorials funda, django for beginners, how to link css,js and images in django template, how to link static files in django, load static in django, how to register static files in settings file in django

© Copyright - 2018 - 2021 | All rights reserved at Funda of Web IT