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 Variables

In Django templates, variables are used to display dynamic content based on the data passed from views. This tutorial will guide you through the basics of using variables in Django templates.

  • Create a template: In your app's templates directory, create a new HTML file named user_profile.html. Add placeholders for the variables that will be used in the template:
<!DOCTYPE html>
<html>
<head>
    <title>User Profile - {{ user.username }}</title>
</head>
<body>
    <h1>User Profile: {{ user.username }}</h1>
    <p>Email: {{ user.email }}</p>
    <p>First Name: {{ user.first_name }}</p>
    <p>Last Name: {{ user.last_name }}</p>
</body>
</html>

In Django templates, variables are denoted by double curly braces {{ }}. In this example, we're using the user variable, which contains attributes such as username, email, first_name, and last_name.

  • Create a view: In your app's views.py file, create a view function that renders the template and passes the necessary data as context variables:
from django.shortcuts import render
from django.contrib.auth.models import User

def user_profile(request, user_id):
    user = User.objects.get(id=user_id)
    context = {'user': user}
    return render(request, 'user_profile.html', context)

In this example, we're using Django's built-in User model to fetch the user data based on the user_id parameter. The context dictionary contains the variables that will be passed to the template.

  • Configure URLs: To make the view accessible, configure your app's URLs. In your app's urls.py file, add a new URL pattern that maps to the view function and includes the user_id parameter:
from django.urls import path
from . import views

urlpatterns = [
    path('user_profile/<int:user_id>/', views.user_profile, name='user_profile'),
]

Make sure your app's URLs are included in the project's urls.py file.

  • Test the template variables: Start the Django development server with the python manage.py runserver command. Open a web browser and navigate to the URL corresponding to the view function with a valid user ID (e.g., http://127.0.0.1:8000/myapp/user_profile/1/). You should see the rendered template with the user's data displayed in the variable placeholders.

By using template variables in Django, you can create dynamic web pages that display data passed from your views. You can further enhance your templates with filters and template tags, which allow you to modify and manipulate variable values within the template itself.

  1. How to Use Variables in Django Templates:

    • Description: Variables in Django templates are placeholders for dynamic content that gets replaced when the template is rendered.
    • Code: Example of using variables in a Django template:
      <p>{{ variable_name }}</p>
      
  2. Accessing Context Variables in Django Templates:

    • Description: Context variables are passed from views to templates, providing dynamic data for rendering.

    • Code: Example of accessing context variables in a Django template:

      # views.py
      from django.shortcuts import render
      
      def my_view(request):
          context = {'variable_name': 'Hello, World!'}
          return render(request, 'my_template.html', context)
      
      <!-- my_template.html -->
      <p>{{ variable_name }}</p>
      
  3. Dynamic Variables in Django Templates:

    • Description: Create dynamic content in Django templates by using variables that change based on conditions or user input.
    • Code: Example of using dynamic variables in a Django template:
      <p>{% if condition %}{{ variable1 }}{% else %}{{ variable2 }}{% endif %}</p>
      
  4. Django Template Variable Filters:

    • Description: Django provides filters to modify the presentation of variables in templates, such as formatting, capitalization, etc.
    • Code: Example of using a variable filter in a Django template:
      <p>{{ variable|filter_name }}</p>
      
  5. Using Model Variables in Django Templates:

    • Description: Access variables from Django models in templates to display data from the database.

    • Code: Example of using model variables in a Django template:

      # models.py
      from django.db import models
      
      class MyModel(models.Model):
          name = models.CharField(max_length=100)
      
      <!-- my_template.html -->
      <p>{{ my_model_instance.name }}</p>
      
  6. Built-In Template Variables in Django:

    • Description: Django provides built-in variables like {{ user }}, {{ request }}, and others, which can be used in templates.
    • Code: Examples of using built-in variables in Django templates:
      <p>{{ user.username }}</p>
      
  7. Debugging Variables in Django Templates:

    • Description: Debugging variables involves printing or inspecting their values to identify issues in template rendering.
    • Code: Example of debugging variables in Django templates:
      {% debug %}
      
  8. Escaping Variables in Django Templates:

    • Description: Prevent security issues by properly escaping variables in templates to avoid code injection.
    • Code: Example of escaping variables in a Django template:
      <p>{{ unsafe_variable|safe }}</p>