Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django Template System

Django's template system allows you to separate presentation logic from the application logic, making your code more maintainable and reusable. This tutorial will guide you through the basics of Django's template system.

  • Create a Django app: Before working with templates, you need to have a Django app set up. If you haven't already, create a new app within your Django project by running the following command:
python manage.py startapp myapp

Replace myapp with your desired app name.

  • Create a templates directory: By default, Django looks for templates in a folder named templates within each app. Create a new folder named templates inside the myapp folder.

  • Create a template: Inside the templates folder, create a new file named index.html. This file will serve as a simple template for this tutorial. Add the following HTML code to the file:

<!DOCTYPE html>
<html>
<head>
    <title>My Django App</title>
</head>
<body>
    <h1>Welcome to My Django App!</h1>
    <p>{{ message }}</p>
</body>
</html>

In Django templates, you can use double curly braces {{ }} to insert the value of a variable. In this case, we're inserting the value of the message variable.

  • Create a view: Open the myapp/views.py file and create a new view function that will render the index.html template:
from django.shortcuts import render

def index(request):
    context = {'message': 'Hello, Django Template System!'}
    return render(request, 'index.html', context)

The render() function takes the request object, the template name, and an optional dictionary called context. The context dictionary contains variables that will be passed to the template.

  • Configure URLs: To make the view accessible, you need to configure URLs for your app. In the myapp folder, create a new file named urls.py and add the following code:
from django.urls import path
from . import views

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

Then, include your app's URLs in the project's urls.py file:

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

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

This will make the index view accessible at the /myapp/ path.

  • Test your template: Start the Django development server with the python manage.py runserver command, and navigate to http://127.0.0.1:8000/myapp/ in your web browser. You should see the rendered index.html template, with the message "Hello, Django Template System!" displayed.

With the basic template system set up, you can start exploring more advanced features like template inheritance, filters, and custom template tags. The Django template system provides a powerful and flexible way to manage your application's presentation logic.

  1. Django Template Tags and Filters:

    • Description: Django template tags and filters are used to perform logic, control flow, and manipulate data within templates.
    • Code: Example of using tags and filters in a Django template:
      {% if user.is_authenticated %}
          <p>Welcome, {{ user.username }}!</p>
      {% else %}
          <p>Please log in</p>
      {% endif %}
      
  2. Getting Started with Django Templates:

    • Description: Django templates are used to generate dynamic HTML content based on data from views.
    • Code: Basic Django template structure in an HTML file:
      <!DOCTYPE html>
      <html>
      <head>
          <title>{{ title }}</title>
      </head>
      <body>
          <h1>Hello, {{ user.username }}!</h1>
      </body>
      </html>
      
  3. Django Template Inheritance Explained:

    • Description: Template inheritance allows creating a base template with common structure and extending it in other templates.

    • Code: Example of a base template and an extended template:

      <!-- base_template.html -->
      <!DOCTYPE html>
      <html>
      <head>
          <title>{% block title %}Default Title{% endblock %}</title>
      </head>
      <body>
          <div id="content">
              {% block content %}{% endblock %}
          </div>
      </body>
      </html>
      
      <!-- extended_template.html -->
      {% extends 'base_template.html' %}
      
      {% block title %}Extended Title{% endblock %}
      
      {% block content %}
          <h1>Hello, {{ user.username }}!</h1>
      {% endblock %}
      
  4. Django Template Context Variables:

    • Description: Context variables are passed from views to templates and provide dynamic data for rendering.
    • Code: Example of passing context variables from a view to a template:
      # views.py
      from django.shortcuts import render
      
      def my_view(request):
          context = {'user': request.user, 'title': 'My Page'}
          return render(request, 'my_template.html', context)
      
  5. Conditional Statements in Django Templates:

    • Description: Conditional statements in Django templates allow controlling the display of content based on logical conditions.
    • Code: Example of using if conditions in a Django template:
      {% if user.is_authenticated %}
          <p>Welcome, {{ user.username }}!</p>
      {% else %}
          <p>Please log in</p>
      {% endif %}
      
  6. Iterating Over Lists in Django Templates:

    • Description: Use the {% for %} loop to iterate over lists or querysets in Django templates.
    • Code: Example of iterating over a list in a Django template:
      <ul>
          {% for item in my_list %}
              <li>{{ item }}</li>
          {% endfor %}
      </ul>
      
  7. Including Templates in Django:

    • Description: Use the {% include %} tag to include other templates within a template.

    • Code: Example of including a template in another template:

      <!-- included_template.html -->
      <p>This is an included template</p>
      
      <!-- main_template.html -->
      <h1>Main Template</h1>
      {% include 'included_template.html' %}
      
  8. Django Template Built-In Filters:

    • Description: Django provides built-in filters for manipulating and formatting template variables.
    • Code: Example of using a built-in filter in a Django template:
      <p>{{ some_variable|default:"No value" }}</p>
      
  9. Django Template Custom Filters:

    • Description: Define custom template filters to extend the functionality of Django templates.

    • Code: Example of creating a custom filter:

      # custom_filters.py
      from django import template
      
      register = template.Library()
      
      @register.filter(name='double')
      def double(value):
          return value * 2
      
      <!-- template.html -->
      <p>{{ some_variable|double }}</p>
      
  10. Django Template Variables and Expressions:

    • Description: Django template variables and expressions allow dynamic content based on data from views.
    • Code: Example of using variables and expressions in a Django template:
      <p>Total: ${{ price * quantity }}</p>
      
  11. Django Template for Loops and If Conditions:

    • Description: Combine for loops and if conditions in Django templates for complex rendering logic.
    • Code: Example of using both for and if in a Django template:
      {% for item in my_list %}
          {% if item.is_available %}
              <p>{{ item.name }} is available</p>
          {% endif %}
      {% endfor %}
      
  12. Dynamic Content in Django Templates:

    • Description: Django templates support dynamic content by rendering data dynamically based on the context.
    • Code: Example of rendering dynamic content in a Django template:
      <h1>{{ page_title }}</h1>
      <p>{{ page_content }}</p>