Loading, please wait...

A to Z Full Forms and Acronyms

How to use Static files in DJango?

Jul 26, 2020 django, python, web development, 2200 Views
learn how to insert static media files

so far we've used templates to insert simple text (please refer to my previous article ) but we don't always just want text, what about other types of media, for example, returning a user's Photo?

Static content is any content that can be delivered to an end-user without having to be generated, modified, or processed. The server delivers the same file to each user, making static content one of the simplest and most efficient content types to transmit over the Internet.

How static content works

Fetching a static asset from a server is one of the basic functions of the web. For example, typing the following URL in a web browser (http://www.example.com/index.html) fetches the file index.html from the server hosting example.com.

There are three steps to requesting static content from a server:

1. A user sends a request for a file to the webserver.
2. The web server retrieves the file from disk.
3. The web server sends the file to the user.

Any kind of file can be served as static content as long as it does not change in response to a user’s actions or inputs. This includes images, JavaScript files, CSS files, videos, Flash files, even web pages.

so lets discuss static media files!! in django..To do this we will create a new directory inside of the project called static (just like we did for template)
then we will add this directory path to the project's settings.py file

we will also add a STATIC_URL VARIABLE

Once we've done that we need a place to store our static image files we create a directory inside of static called images to place a  .jpg file inside this images directory(or just download one )

to test that this all worked you can go to:-

In a similar manner, we can create a directory for CSS files as well as javascript files and repeats the same set of tasks above to add static content.

For example in my CSS file, I have

    color: red;

and then we will add this CSS file inside our index.html using template tags 

<!DOCTYPE html>
{% load static %}
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>first app static file </title>
 <!-- adding css file -->
    <link rel="stylesheet" href="{% static 'css/style.css' %}">

    <h1>hello this is index.html! example of static file  </h1>
    <!-- {{ insert_me }} template tag -->
    <img src="{% static 'images/header.png' %}" alt="My image">

and then start your server by using the command python manage.py runserver

A to Z Full Forms and Acronyms

Related Article