In this blog we will look that how can you resolve the Static File Error in New Version of Django or specifically django 3.1 and new version.
If you are using any earlier version of django such as 3.0 and 2.0 , then I prefer that this blog is not for you. But yaah if you want to have better understanding with django static file then you should pursue it further.
Brief Introduction to Static Files :-
Static files like CSS, JavaScript, Images and fonts are a core piece of any modern web application. Django provides flexibility around how these files are used, however this often leads to confusion for newcomers.
A single Django project often contains multiple apps. By default, Django will look within each app for a static directory containing static files. So if one of your apps was called shop and you wanted to add a CSS file to it called style.css you need to first create a new directory called shop/static/shop and then add the file within it so the location would be shop/static/shop/style.css.
Error Solving Process :-
So now here you have a static folder in your application where your all static files are located but you yet not tell about it to President of the home, I mean to settings.py.
So let's open settings.py file located in your project directory and let's have a look on it that what changes are their in django 3.1 or above version.
- At the top of settings.py file you will see the some import statement and BASE_DIR path which are quit different from older version of django.
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
- django project ,
- django application
- manage.py
STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles'))
STATICFILES_DIR =[str(BASE_DIR.joinpath('static'))]
Static file in django template:-
<link rel="stylesheet" href="{% static 'shop/style.css' %}"> <script src="{% static 'shop/index.js' %}"></script>
from django.conf import settingsfrom django.conf.urls.static import static
urlpatterns = [ ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Here you are configuring the urls of static location which you have just create in settings.py file.
So that is up here your static file error in new version of django it solved and static files configuration is now absolutely fine and working well.
Thanku for reading this blog,
Happy Learning
0 Comments
If you have any doubt, Let me Know
Emoji