top of page

Django Templates - p4n topic

Updated: Jun 29, 2023

A template in Django is basically written in HTML, CSS, and Javascript in a .html file. Django framework efficiently handles and generates dynamically HTML web pages that are visible to the end-user. Django mainly functions with a backend so, in order to provide a frontend and provide a layout to our website, we use templates. There are two methods of adding the template to our website depending on our needs. We can use a single template directory which will be spread over the entire project. For each app of our project, we can create a different template directory.

For our current project, we will create a single template directory that will be spread over the entire project for simplicity. App-level templates are generally used in big projects or in case we want to provide a different layout to each component of our webpage.


Creating a template in Django involves a few simple steps. Here's an example of how to create a template in Django:

1. Create a Django app (if you haven't already):


python manage.py startapp myapp

2. Inside your app directory, create a folder called "templates":


myapp/
    └── templates/

3. Within the "templates" folder, create another folder with the name of your app (e.g., "myapp"):


myapp/
    └── templates/
        └── myapp/

4. Inside the app-specific template folder ("myapp" in this example), create your template file. Let's say we create a file called "index.html":


myapp/
    └── templates/
        └── myapp/
            └── index.html
            

5. Open the "index.html" file and start writing your HTML code. You can use Django template tags and filters to dynamically render data. For example, you can use {{ variable_name }} to display dynamic data passed from a view.


<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Codeswithpankaj</title>
</head>
<body>
    <h1>Welcome to my Django App!</h1>
    <p>The current time is: {{ current_time }}</p>
</body>
</html>

6. In your Django views, pass data to the template and render it. For this example, let's assume we have a view called "index" in "myapp/views.py":


from django.shortcuts import render
from datetime import datetime

def index(request):
    current_time = datetime.now()
    return render(request, 'myapp/index.html', {'current_time': current_time})

7. Finally, define a URL pattern in your app's "urls.py" file to map the view to a URL:


from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

That's it! Now, when you navigate to the URL mapped to the index view, Django will render the "index.html" template and pass the current time data to it.



Related Posts

See All

Comments


bottom of page