Django / Django Basics
Exploring Models, Views, and Templates
In this tutorial, we'll deep dive into Django's MVT (Model, View, Template) architecture. You'll learn how to define your data model, create views to handle the business logic, an…
Section overview
5 resourcesCovers the fundamental concepts of Django, including project structure, models, views, and templates.
Introduction
Welcome to this tutorial where we will explore Django's MVT (Model, View, Template) architecture. Our primary focus will be on defining your data model, creating views to manage the business logic, and designing templates to control the presentation of your data.
You will learn:
- The basics of Django's MVT architecture.
- How to create and utilize models.
- How to create views and templates.
- How to link all these components together in a Django project.
Prerequisites:
- Basic knowledge of Python
- Basic understanding of Django framework
Step-by-Step Guide
Django MVT Architecture
Django MVT (Model-View-Template) is a software design pattern. It's a collection of three important components Model View and Template. The Model helps to handle the database. It's a data access layer which handles the data. The View is used to execute the business logic and interact with a model to carry data and renders a template. The Template is a presentation layer which handles User Interface part completely.
Models
A model is a representation of your data structure. It’s a Python object that is mapped to a database table. Django gives you a high-level, Pythonic interface to your database tables, taking care of the SQL for you.
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
def __str__(self):
return self.title
In this example, we have created a Blog model with a title field (limited to 200 characters) and a description field (a text field with no character limit).
Views
Views handle the business logic of your application. They receive HTTP requests from the user, interact with the model to get the requested data, and then render the appropriate template with this data to generate an HTTP response.
from django.shortcuts import render
from .models import Blog
def blog_list(request):
blogs = Blog.objects.all()
return render(request, 'blog/blog_list.html', {'blogs': blogs})
In this example, we have a view blog_list that fetches all the Blog objects from the database and passes them to the blog_list.html template.
Templates
Templates are the presentation layer in the MVT pattern. They define how the data should be presented to the user.
{% extends 'base.html' %}
{% block content %}
<h2>Blog List</h2>
{% for blog in blogs %}
<h3>{{ blog.title }}</h3>
<p>{{ blog.description }}</p>
{% endfor %}
{% endblock %}
This template extends a base template (base.html) and replaces its content block with a list of blogs.
Code Examples
Let's create a simple blog application as an example.
Models
# models.py
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
def __str__(self):
return self.title
Here, we have a Blog model with title and description fields.
Views
# views.py
from django.shortcuts import render
from .models import Blog
def blog_list(request):
blogs = Blog.objects.all() # Fetch all blog objects
return render(request, 'blog/blog_list.html', {'blogs': blogs}) # Pass them to the template
In our view, we fetch all the Blog objects and pass them to the blog_list.html template.
Templates
<!-- blog_list.html -->
{% extends 'base.html' %}
{% block content %}
<h2>Blog List</h2>
{% for blog in blogs %}
<h3>{{ blog.title }}</h3>
<p>{{ blog.description }}</p>
{% endfor %}
{% endblock %}
The template receives the blogs context variable from the view and displays each blog's title and description.
Summary
In this tutorial, we covered the basics of Django's MVT architecture. We learned about models, views, and templates, and how they interact with each other. We also created a simple blog application as an example.
Next, try to extend our blog application. Maybe add a feature to create new blogs, or add a detail view where users can read one blog at a time.
Practice Exercises
- Create a new model
Authorwith fieldsnameandbio. Modify theBlogmodel to include a foreign key toAuthor. - Create a new view and template to display all blogs by a specific author.
- Add a feature to create new authors.
Solutions, explanations, and tips for these exercises will be provided in the next tutorial. Keep practicing and happy coding!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article