Static File Handling in Django
Files that can’t be handled, created, or updated by the server are known as static files. Images, CSS files, JavaScript files, and other static files are examples of content. Until the developer replaces them with a new one, these files remain unchanged. As a result, the server just gets them from the disc, which takes very little time.
Static files can contain a wide range of file types, including.mpeg,.jpeg, and.pdf, among others. Working with static files has a basic notion. The server will generate HTML when a user requests a webpage. The server will then collect all of the static files associated with that page. Finally, the entire data is served.
The management of static files is crucial in web development. This scenario necessitates developers to manage static files when the website undergoes frequent UI modifications and visuals are updated on a regular basis. Django includes a static file handler by default. It’s a simple concept that requires some tweaking of the settings.py.
If you check the list of INSTALLED_APPLICATIONS in settings.py file, we can see an application listed as ‘django.contrib.staticfiles’. Moving to the next phase, we have STATIC_URL variable in the last section of the page. This URL is crucial since it will serve as the starting point for all static files in your project.
The name of this URL should match the name of the folder in which your static file is located. Then there’s STATIC ROOT, which is a crucial setting. This parameter specifies the location of the folder where static files will be stored. Last but not least, STATICFILES DIRS is a directory list. This list contains the file paths to the directories where our static files are stored. The files will be saved in our STATIC ROOT folder after that.
STATIC_URL = ‘/static/’
STATIC_ROOT = os.path.join(BASE_DIR, ‘root’)
STATICFILES_DIRS = [os.path.join(BASE_DIR, ‘static’)]
The HTML file should include {% load static %} tag that will inform Django that there are static files in this template. Django will then check for the related static files. Then sends them together with the HTML code.
Best python training in Kochi will provide the best training in all about Static file handling while creating the web applications. Choose a Python full stack developer training in Kochi that will help you to reach the heights in your career.