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.
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).
First, let's set up the necessary configurations in our settings.py file:
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.
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:
body {
background-color: lightblue;
}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:
{% 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.
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! π