DEV Community

Cover image for Mastering Django: How to Render HTML Like a Pro!
Oviyan S
Oviyan S

Posted on

Mastering Django: How to Render HTML Like a Pro!

Hello everyone welcome back to another interesting blog. Today we will learn how to add static files and templates to our Django web app.

What are Static files?
Static files are nothing but in our folder with all CSS files, JS files and images required for our web app.

Before that, we will learn about how to execute the Hello World in web app. Already we left with Django installation.

Let's learn practically!!!

create the view function for displaying the Hellow world. For that navigate to views.py and create the Python functions to return the HTTP response.



from django.shortcuts import render,HttpResponse


def home(request):
    return HttpResponse("Hello World!!!")



Enter fullscreen mode Exit fullscreen mode

Everything is ready now We have to map this view function to the URLs.py


from django.contrib import admin
from django.urls import path
from home import views 

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.home), 
]


Enter fullscreen mode Exit fullscreen mode

Run the server and open it

in the web browser yay!!!! we got the output.

output

How to render the HTML file

we know every website runs based on an HTML file our web app is also the same and for that, we have to render our template aka HTML file.

Create the template folder inside the app that creates
the HTML file you want.

*Folder Structure of App *

file structure

add the code to the index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <h1>Yay!!!! I'm from templates</h1>


</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Link the HTML file to the views.py All set run the server to see the output

``

from django.shortcuts import render,HttpResponse

def home(request):
return render(request,"index.html")

``

Start the development server and open that link in the browser
BOOM !!!!

we can see the output

Image description

Connect With Me: Linkedin

Top comments (0)