DEV Community

Shrikant Dhayje
Shrikant Dhayje

Posted on • Originally published at codewithshriekdj.netlify.app on

Creating HTML Template And Views | Django CMS Building By shriekdj

In This Post I Will Create Html Pages for the site and as well as show how to use urls.py and views.py.

First Create a folder named templates in blog app in django app and add update the variable in django_project_name/setting.py like given below

import os # add it at the top of settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')], # at here add templates folder
        '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',
            ],
        },
    },
]
Enter fullscreen mode Exit fullscreen mode

Create an index.html in it like given below

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World</title>
</head>
<body>
    <h1>Hello World</h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now goto file blog/views.py and create a new function like below to load our index.html you can give whatever name you wanted.

from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request, 'index.html')
Enter fullscreen mode Exit fullscreen mode

Here we are rendering our index page with function named index. it's not mandatory to give the same name as file name but it's just helps you remember the locations. at above function we are giving parameter request it is for getting the data from our client browser and we as Server write logic at in this function.

We Also Need 2 More Steps to view this page.

First Create urls.py in blog folder and write below code.

from django.urls import path
from blog import views

urlpatterns = [
    path('', views.index)
]
Enter fullscreen mode Exit fullscreen mode

at here we are loading all the urls in urlpatterns variable and blank path means that it's at homepage of blog app.

And At Last At the django_project/urls.py we need to make some modifications. Watch Clearly Both Are same file name but different Folder. This urls.py is Main url routing file of whole site. change it like given below

from django.contrib import admin
from django.urls import include ,path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls'))
]
Enter fullscreen mode Exit fullscreen mode

At here we have to Add Global Paths of Site with Special include function. directly adding similar to admin will not work. now load the site with python ./src/manage.py runserver screenshot given below.

Django's Index Page Loading Image

if you see this clearly i did not use relative import it may raises some error in production mode in future and i have to manually update all relative import to absolute import.

But I Will Mostly Use Class Based Views Instead of Function Based so I will Change My index function in `views.py as follows.

`python
from django.shortcuts import render
from django.views import View

Create your views here.

class IndexView(View):

def get(self, request, *args, **kwargs):
    return render(request, 'index.html')
Enter fullscreen mode Exit fullscreen mode

`

Here all the logic of the code get into get method the views class and also change urlpatterns under blog/urls.py as follows below.

`python
from django.urls import path
from blog import views

urlpatterns = [
path('', views.IndexView.as_view(), name='index_view'),
]
`

It will not change look of the page at all as of now but in future we can use inheritance like features with it.

In Class View The get method means GET Request and obviously it have other request methods like ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

and as_view() method will return the response as per request method in one class.

Chaging View Again

`python
from django.views.generic.base import TemplateView

Create your views here.

class IndexView(TemplateView):

template_name: str = 'index.html'

# def get(self, request, *args, **kwargs):
#   return render(request, 'index.html')
Enter fullscreen mode Exit fullscreen mode

`

you can seet the code it reduced if we are returning the render function.

Actually views function have the specific way of returning pages like given below.

python
def my_view_function(request):
context_to_send_html= {"data sent to our template": "some-data" }
return render(request, 'template_file_name.html', context_to_send_html)

To Make It Easily Writable We Write Class Based View. as of now it look to difficult but it will save too much of our time in future.

As always the given below is GitHub Repository URL.

shriekdj_cms build in django

Top comments (0)