Django Tutorial: Understanding STATIC_URL and STATICFILES_DIRS

beginner
12 min

Django Tutorial: Understanding STATIC_URL and STATICFILES_DIRS

Welcome to our comprehensive Django tutorial on STATIC_URL and STATICFILES_DIRS! Let's dive into this essential topic that will help you manage static files like CSS, JavaScript, and images in your Django projects.

What are STATIC_URL and STATICFILES_DIRS? πŸ’‘

In Django, STATIC_URL is a setting that defines the URL prefix for static files, while STATICFILES_DIRS is a list of additional directories where Django should search for static files, apart from the static files found in the STATICFILES_DIR (usually located at your_project/static).

Setting Up STATIC_URL and STATICFILES_DIRS πŸ“

First, let's set up the necessary configurations in our settings.py file:

python
STATIC_URL = '/static/' STATICFILES_DIRS = [ base/'static', ]

In the above code snippet, we set STATIC_URL to '/static/', which means our static files will be accessible through this URL prefix in our web application. We also define STATICFILES_DIRS to include the 'base/static' directory, which is where we will keep our static files.

Creating a Static File 🎯

Now that our configuration is in place, let's create a simple static file, such as a CSS file called styles.css in our base/static/css directory. Add the following content:

css
body { background-color: lightblue; }

Incorporating Static Files in Templates πŸ“

To use the styles.css file in our template, we need to include it in the HTML file using the {% load static %} tag and the {% static %} filter. Create a new HTML file in base/templates/base.html with the following content:

html
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Django STATIC_URL & STATICFILES_DIRS Example</title> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> </head> <body> <!-- Your HTML content goes here --> </body> </html>

Now, when you run your Django development server and navigate to your web application, you should see the background color change to light blue, thanks to the styles.css file we created earlier.

Quiz Time! βœ…

Quick Quiz
Question 1 of 1

What does the `STATIC_URL` setting do in Django?

We hope you enjoyed this tutorial on STATIC_URL and STATICFILES_DIRS in Django. In our next tutorial, we'll explore more advanced topics like using collectstatic and customizing the media upload settings. Stay tuned! πŸš€

Happy coding! πŸŽ‰