Django-Project static and templates tutorial part-2

Python-Django Framework

Posted by indranil on March 10, 2021, 11:49 p.m.

Here i am showing you how to render your html file on templates folder. In this previous post i show you how to create web-app for your django-project?

If you already setup your enviroment and create  your web-app on your django-project and run on your local server then we need to render html page on our templates folder and access static folder.

what is templates and static django-project?

         well templates is your base directory here you can store your html file and render on your django-project. and static folder is stored your css, js file and you can access also img for create your html page and look like better view. Lets get practical.

Create templates and static folder on your django-project

Your django-project stracture like 

django-project/
    manage.py
    djangoproject/
home/

static/
templates/
db.sqlite3

Now create a simple html page on your templates folder index.html 

Lets open your index.html and write your script, here i am using simple bootstrap script.

index.html

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

    <title>Django Tutorial!</title>
  </head>
  <body>
    <h1>Our First Django-webapp run on local server!</h1>

    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>
    -->
  </body>
</html>

 

How to render html page from templates for our django-project?

Before rendering html file we need a simple changes on our settings.py file. Lets Open settings.py 

settings.py 

Add Your: 'DIRS' : [], ------->> 'DIRS' : ['templates'], Or Replace All TEMPLATES code

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Now get back to your app home/views.py file. Here you access your html page.

views.py

from django.shortcuts import render, redirect, HttpResponse
import datetime

def homeIndex(request):
    
   
return render(request,'index.html')

def testIndex(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

def test1Index(request):
    return HttpResponse('Test1')

def test2Index(request):
    return HttpResponse('Test-2')

How to access static page from templates for our django-project?

Ope your django-project project directory

django-project/djangoproject/settings.py

settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = (

    os.path.join(BASE_DIR, 'static'),

)

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

django-project/djangoproject/urls.py

urls.py

from django.contrib import admin

from django.urls import path, include

from django.conf import settings

from django.conf.urls.static import static

urlpatterns = [

    path('admin/', admin.site.urls),

    

    path('', include('home.urls') ),

]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Now create test.txt for simple test your static file On your

Open directory django-project/static/test.txt

This is the test static file.........

Open directory django-project/templates/index.html

 

static folder is a opensource folder for your django project. you can access all static files of simple python syntex. 

Load your static file simple this command  {% load static %} this command is allow to access static file.

And serve or get your static folder by {%static 'your_static_file_name' %}

index.html

<!doctype html>

{% load static %}

<html lang="en">

  <head>

    <!-- Required meta tags -->

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

    <title>Django Tutorial!</title>

  </head>

  <body>

    <h1>Our First Django-webapp run on local server!</h1>

    <a href="{%static 'test.txt' %}">Click me to get static</a>

    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->

    <!--

    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>

    -->

  </body>

</html>

How to render multyple html page with multyple Link?

we should to learn how to to render html page with unique way. Its means here we create html page for our apps views.

Now open your templates directory on your django project

django-project/templates/

Create New directory(folder) home

Create New file base.html

now we get access templates/home this directory from our apps views 

   

django-project/templates/base.html

<!doctype html>
{% load static %}

<html lang="en">

<head>

    <!-- Required meta tags -->

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"

        integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

    <title>{% block title %} {% endblock title %}</title>

</head>

<body>

    <nav class="navbar navbar-expand-lg navbar-light bg-light">

        <div class="container-fluid">

            <a class="navbar-brand" href="#">Coder-i test tutorial</a>

            <button class="navbar-toggler" type="button" data-bs-toggle="collapse"

                data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"

                aria-label="Toggle navigation">

                <span class="navbar-toggler-icon"></span>

            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">

                <ul class="navbar-nav me-auto mb-2 mb-lg-0">

                    <li class="nav-item">

                        <a class="nav-link active" aria-current="page" href="/">Home</a>

                    </li>

                    <li class="nav-item">

                        <a class="nav-link active" aria-current="page" href="/Test/">Test</a>

                    </li>

                    <li class="nav-item">

                        <a class="nav-link active" aria-current="page" href="/Test-1/">test1</a>

                    </li>

                    

                    <li class="nav-item">

                        <a class="nav-link active" aria-current="page" href="/Test-2/">test2</a>

                    </li>

                    

                </ul>

                <form class="d-flex">

                    <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">

                    <button class="btn btn-outline-success" type="submit">Search</button>

                </form>

            </div>

        </div>

    </nav>

    {% block body %}

    {% endblock %}

    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js"

        integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0"

        crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->

    <!--

    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>

    -->

</body>

</html>

django-project/templates/home/

index.html

{% extends 'base.html' %}

{% load static %}

{% block title %} home {% endblock title %}

{% block body %}

This is our home page 

{% endblock %}

test.html

{% extends 'base.html' %}

{% load static %}

{% block title %}test {% endblock title %}

{% block body %}

This is our test page 

{% endblock %}

test1.html

{% extends 'base.html' %}

{% load static %}

{% block title %}test1 {% endblock title %}

{% block body %}

This is our test1 page 

{% endblock %}

test2.html

{% extends 'base.html' %}

{% load static %}

{% block title %}test2 {% endblock title %}

{% block body %}

This is our test2 page 

{% endblock %}

Now open your app directory on your django project

django-project/home/urls.py

urls.py

from django.urls import path

from . import views

urlpatterns = [

   

    path('', views.homeIndex, name='homeIndex'),

    path('Test/', views.testIndex, name='testIndex'),

    path('Test-1/', views.test1Index, name='test1Index'),

    path('Test-2/', views.test2Index, name='test2Index'),

]
django-project/home/views.py

views.py

from django.shortcuts import render, redirect, HttpResponse

import datetime


# Create your views here.

def homeIndex(request):

    

    return render(request, 'home/index.html')

def testIndex(request):

    

    return render(request, 'home/test.html')

def test1Index(request):

    return render(request, 'home/test1.html')

def test2Index(request):

    return render(request, 'home/test2.html')

Related Question

What is djanngo-project model folder?

How to create simple model for our project?

noimg Visit Link: digitalocean.com