Welcome to our comprehensive Django tutorial! In this lesson, we'll delve into Django's unique features, its Model-View-Template (MVT) architecture, and how to build a real-world project. Let's get started!
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It's built by experienced developers and takes the best of other frameworks to create a powerful and flexible tool.
Django offers several advantages such as:
Django's MVT architecture is a way to structure web applications. It separates the application logic into three main components:
Let's create a simple project and see how these components work together.
First, you need to install Django using pip:
pip install djangoCreate a new Django project:
django-admin startproject my_projectNow, let's create a new app:
cd my_project
python manage.py startapp my_appOpen my_app/models.py and define a simple model:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_date = models.DateField()Run the following command to apply the database migration:
python manage.py makemigrations my_app
python manage.py migrateOpen my_app/views.py and create a simple view:
from django.http import HttpResponse
from my_app.models import Book
def book_list(request):
books = Book.objects.all()
output = '<ul>'
for book in books:
output += f'<li>{book.title}, {book.author}, {book.publication_date}</li>'
output += '</ul>'
return HttpResponse(output)Open my_app/urls.py and define a URL for the view:
from django.urls import path
from . import views
urlpatterns = [
path('books/', views.book_list, name='book_list'),
]Open my_project/urls.py and include the app's URLs:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('my_app.urls')),
]Start the development server:
python manage.py runserverNow, if you navigate to http://127.0.0.1:8000/books/, you'll see a list of books generated by our simple view!
We've covered the basics of Django, its MVT architecture, and how to create a simple project. In the next lessons, we'll delve deeper into Django, exploring templates, forms, and more advanced topics.
What is the purpose of Django's MVT architecture?