Skip to main content

Write HTML Templates

Why to write HTML Templates

Till now the APIs are ready but app needs HTML templates to show data. In django, you can embed Python code within HTML tags, making it easy to generate dynamic content based on data retrieved from a database or other sources.

Introduction to Django Templates

Django templates are a way of generating dynamic HTML web pages in a Django web application. Django templates use a syntax that allows you to embed Python code within HTML tags, making it easy to generate dynamic content based on data retrieved from a database or other sources.

To use Django templates in your Django application, you will need to create template files and specify how they are rendered within your views.

Steps to Write Templates

Here's a simple example of how you can create a Django template:

  • Create a new directory called "templates" within your Django application directory.
  • Within the templates directory, create a new file called "fileName.html".
  • Add HTML code to the "fileName.html" file:

Lets Start

In this app, I will create templates for user authentication and posts.

SignUp Template

blog/templates/signup.html
<html>
<head>
<title>SignUp</title>
</head>
<body>
<h1>SignUp</h1>
<form method="post">
{% csrf_token %} {{signupForm}}
<button type="submit">Submit</button>
</form>
</body>
</html>

I already explaind csrf_token in previous topics.

Login Template

blog/templates/signin.html
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method="post">
{% csrf_token %} {{loginForm}}
<button type="submit">Submit</button>
</form>
</body>
</html>

Create Post Template

blog/templates/create_post.html
<html>
<head>
<title>Create Post</title>
</head>
<body>
<h1>Create Post</h1>
<form method="post">
{% csrf_token %} {{postForm}}
<button type="submit">Submit</button>
</form>
</body>
</html>

Get All Posts Template

blog/templates/posts.html
<html>
<head>
<title>Posts</title>
</head>
<body>
<h1>Posts</h1>
<ul>
{% for post in posts %}
<li><a href="/blogs/post/{{post.id}}">{{post.title}}</a></li>
<li>{{post.author.username}}</li>
{%endfor%}
</ul>
</html>

Get Post Detail Template

blog/templates/post_detail.html
<html>
<head>
<title>Post Detail</title>
</head>
<body>
<h1>Posts Detail</h1>
<ul>
<li><a href="/posts/{{post.id}}">{{post.title}}</a></li>
<li>{{post.author.username}}</li>
<li>{{post.content}}</li>
<li>{{post.date}}</li>
<li>{{post.time}}</li>
<li>{{post.image}}</li>

{%if comments%}
Reply to this comment
<ul><li>
{% for reply in comments %}
{{reply.comment}}
{{reply.author}}
{{reply.date}}
{{reply.time}}
</li></ul>
{%endfor%}
{%endif%}
</ul>
<h3> Post a new Comment to this Post</h3>
<form action="/blogs/post/{{post.id}}/comments/" method="post">
{% csrf_token %} {{commentForm}}
<button type="submit">Submit</button>
</form>
</html>