How render to a html file in django

By Guru - May 13, 2021



Render a HTML file




How Render a Html file in Django? 

I consider you have create a project and app to proceed further, if not
you get it done from here project and app.
To render a html file we first need to create a directory called templates inside your app directory.



now create a html file home.html inside this templates.

<!--home.html-->

<!DOCTYPE html>
<html lang="en">
<head>
<title>Django app</title>
</head>
<body>
<h1 style="text-align: center;">HELLO WORLD!</h1>
</body>
</html>


after create a html file, its time to create a view for this html file.
so in myapp-> views.py create a function like this.

#views.py

from django.shortcuts import render

# Create your views here.
def home(request):
return render(request,'home.html')


now create a path(means url pattern) for view this to render html file.
In app directory create a file named urls.py.

add url pattern as below

#url.py

from django.contrib import admin
from django.urls import path
# importing views from views..py
from myapp import views
urlpatterns = [
path('home', views.home, name='home' ),
]


now we need to include this urls to our main project's urls.py

#myproject -> urls.py

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

urlpatterns = [
path('admin/', admin.site.urls),
path('', include("myapp.urls"))
]


now run your server by command:

python manage.py runserver



  • Share:

You Might Also Like

0 Comments