How To Serve Static files in Django

By Guru - May 17, 2021



How To Serve static files



I consider you have create a project and app to proceed further, if not
you get it done from here project and app.

What is static file in Django? 

Static files include stuff like CSS, JavaScript, and images that you may need during working on a project. Django gives you a very organised way to do it and how you should include your static files.

To Add the static files you need put some lines of code in your settings.py in your project root directory.

at the bottom of the settings.py you already see STATIC_URL which append static to base url when searching for the static files.


STATIC_URL = '/static/'


In Django you could have static folder almost anywhere you want. You can have more than one static folder e.g. one in each app. However, for now i will use just one in static folder in the root of the project.

first we add line if code in settings.py, later on we create a folder.

# Add these new lines

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

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')


The STATICFILES_DIRS tuple tells Django where to look for static files that are not tied to a particular app. In this case, we just told Django to also look for static files in a folder called static in our root folder, not just in our apps.

Now its time to create our static directory, so as on same level of project root directory and manage.py, create a directory named static.
Inside static create directory for css and js.
In css create a main.css and in js  create main.js.



Rendering Something to see if it works 

If you know how to render a html file proceed, if not click here.

lets write some code inside the html file.

home.html:

<!--home.html-->

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Django app</title>
<script src="{% static 'js/main1.js' %}"></script>
<link rel="stylesheet" href="{% static 'css/main1.css' %}" type="text/css">
</head>
<body>
<div class="box">
<h1 id="p1" onclick="myfunc()" >HELLO WORLD</h1>
<P>click text above to change color</P>
</div>
</body>
</html>


main.css:

#p1{
color: blue;
}

.box{
margin: 10px;
}


main.js:

function myfunc(){
document.getElementById("p1").style.color = "red";
}


output:


  • Share:

You Might Also Like

0 Comments