Lesson 2: Introduction to Django

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the “batteries-included” philosophy, providing a wide range of features out of the box to help developers build secure, scalable web applications.

Lesson Outline:

  1. Setting Up a Django Project
  2. Models, Views, Templates (MVT Architecture)
  3. URL Routing and Admin Interface

1. Setting Up a Django Project

Installing Django:

  • Use pip to install Django:
    pip install django

Creating a Django Project:

Start a new Django project:
django-admin startproject myproject

cd myproject

  • python manage.py runserver
  • Visit http://127.0.0.1:8000/in your browser to see the default Django welcome page.

Creating an App:

  • Django projects are made up of apps. To create one:
    python manage.py startapp myapp

2. Models, Views, Templates (MVT Architecture)

The MVT (Model-View-Template) architecture is the foundation of Django:

Models: Define the data structure.
from django.db import models

class Book(models.Model):

title = models.CharField(max_length=100)

author = models.CharField(max_length=100)

  • published_date = models.DateField()

Run migrations to create the database tables:
python manage.py makemigrations

  • python manage.py migrate

Views: Handle the business logic and connect models with templates.
from django.http import HttpResponse

def home(request):

  • return HttpResponse(“Welcome to Django!”)
  • Templates:Manage the presentation layer.

Create an HTML file in myapp/templates/:
<!DOCTYPE html>

<html>

<head><title>Home Page</title></head>

<body><h1>{{ message }}</h1></body>

  • </html>

Render this template from the view:
from django.shortcuts import render

def home(request):

  • return render(request, ‘home.html’, {‘message’: ‘Hello, Django!’})

3. URL Routing and Admin Interface

URL Routing:

Define URLs in myapp/urls.py:
from django.urls import path

from . import views

urlpatterns = [

path(”, views.home, name=’home’),

  • ]

Include app URLs in the project’s urls.py:
from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path(‘admin/’, admin.site.urls),

path(”, include(‘myapp.urls’)),

  • ]

Admin Interface:

  • Django comes with a powerful admin interface:
    • Create a superuser:
      python manage.py createsuperuser

Register models in admin.py:
from django.contrib import admin

from .models import Book

  • site.register(Book)
  • Access the admin panel at http://127.0.0.1:8000/admin/.

Conclusion:

This lesson covered setting up a Django project, understanding the MVT architecture, routing URLs, and using the built-in admin interface. Django’s structured approach simplifies web development, making it a robust choice for complex projects.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *