Using Django Static Files

Introduction

 
In this chapter, you will learn how to use static files with Django.
 

Static Files 

 
In the Django framework, static files mean the use of CSS, js, images folder location using the static keyword. The static keyword defines the location of these files. But first, we have to configure the path of static file using settings.py file.
  1. In this chapter, we will use the bootstrap framework with Django. So firstly for the use of bootstrap, we have to configure static files location and then use it in the template.
     
  2. Open the settings.py file and add some lines in below of settings.py file as below images.
     
    code
     
  3. Now create a static folder in your Django app folder.
     
  4. Now download the bootstrap framework zip file.
     
  5. Copy all files js, CSS, and fonts folder in the static folder.
     
    folder
     
  6. After this process now we go to HTML files that I already told you about.
     
  7. Add bootstrap file in HTML using static keywords.
     
    keywords
     
  8. The above image shows some code in the HTML file.
     
  9. {% load staticfiles %} is used for loading all static files here for use and second {% static ‘css/bootstrap.min.css’ %} in the link tag is used for giving the path of CSS file that can automatically inherit this CSS file and in below js file is also added using the same syntax so this helps for set path automatically without custom URL.
     
  10. Now we create some bootstrap components in this HTML file.
     
    html file
     
  11. Now run the Django project and open the URL of using your urls.py, then you will get output on a webpage.
     
    output
     
  12. It means all CSS, js files are working properly and now open and inspect the element of the browser and see the location of files.
     
    code
     
  13. Here static denotes insettings.py files as STATIC_URL=”/static/”
So here you can insert any CSS, js, and fonts file and attach using static keyword in HTML file.
 
Note
 
When you deploy a Django project on server static file location is very important. Because many times it creates mostly errors on deployment. So when you deploy project you should have knowledge of server OS types and where is the exact location of your project root.
 

Summary 

 
In the next chapter, you will learn about Django Forms. 
Author
Neeraj Kumar
213 8.1k 2.3m
Next » Django Forms