The following article demonstrates an Example of Connecting Templates with Models in Django.

Basically, in this example we will create a Django app to connect templates with models and serve data dynamically for a Pet Kennel. The following steps need to be followed.

  1. Create a new Django app inside your project.
python manage.py startapp pet_kennel
  1. Open the “models.py” file inside your app’s directory, and define a new model for pets.
from django.db import models

class Pet(models.Model):
    name = models.CharField(max_length=55)
    breed = models.CharField(max_length=200)
    age = models.IntegerField()
    owner = models.CharField(max_length=340)

This creates a new Django model named “Pet” with four fields: name, breed, age, and owner.

  1. Run migrations to create the necessary database tables.
python manage.py makemigrations
python manage.py migrate
  1. Open the “views.py” file inside your app’s directory, and define a new view to display a list of all pets.
from django.shortcuts import render
from .models import Pet

def pet_list(request):
    pets = Pet.objects.all()
    return render(request, 'pet_list.html', {'pets': pets})

This retrieves all pets from the database using the “all()” method on the “Pet” model, and passes them to a new template named “pet_list.html” using a dictionary with a key of “pets”.

  1. Create a new file called “pet_list.html” inside your app’s “templates” directory, and add the following code.
<!DOCTYPE html>
<html>
<head>
    <title>Pet List</title>
</head>
<body>
    <h1>Pet List</h1>
    <ul>
        {% for pet in pets %}
            <li>{{ pet.name }} - {{ pet.breed }} - {{ pet.age }} - {{ pet.owner }}</li>
        {% endfor %}
    </ul>
</body>
</html>

This is a simple HTML template that displays a list of all pets retrieved from the database. The “for” loop iterates over the “pets” context variable passed in from the view, and displays each pet’s name, breed, age, and owner.

  1. Finally, add a URL pattern for your new view in your project’s “urls.py” file.
from django.urls import path
from pet_kennel.views import pet_list

urlpatterns = [
    path('pets/', pet_list, name='pet_list'),
]

This maps the URL “/pets/” to your new view.

Now you can run your Django development server and visit the URL “/pets/” to see a list of all pets displayed dynamically from the database!


Further Reading

Introduction to Django Framework and its Features

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com