Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It was designed to help developers take applications from concept to completion as quickly as possible. In this section, we will cover the basics of Django, including setting up a Django project, understanding its structure, and creating a simple web application.

Key Concepts

  1. Django Framework Overview
  2. Setting Up Django
  3. Django Project Structure
  4. Creating a Simple Django Application
  5. Django Models, Views, and Templates (MVT)
  6. Admin Interface
  7. URL Routing

  1. Django Framework Overview

Django is built on the principle of "Don't Repeat Yourself" (DRY), which means it tries to minimize repetition of code. It follows the Model-View-Template (MVT) architectural pattern.

  • Model: Defines the data structure.
  • View: Controls what data is presented and how it is displayed.
  • Template: Defines the HTML structure of the web pages.

  1. Setting Up Django

Prerequisites

  • Python installed on your system.
  • Basic understanding of Python programming.

Installation

To install Django, use the following command:

pip install django

Verify the installation by checking the Django version:

django-admin --version

Creating a Django Project

To create a new Django project, use the django-admin command:

django-admin startproject myproject

Navigate to the project directory:

cd myproject

  1. Django Project Structure

A Django project consists of several files and directories. Here is an overview of the structure:

myproject/
    manage.py
    myproject/
        __init__.py
        settings.py
        urls.py
        wsgi.py
  • manage.py: A command-line utility that lets you interact with the Django project.
  • settings.py: Configuration file for the project.
  • urls.py: URL declarations for the project.
  • wsgi.py: Entry-point for WSGI-compatible web servers to serve your project.

  1. Creating a Simple Django Application

Creating an App

Inside your project directory, create a new app:

python manage.py startapp myapp

This will create a new directory myapp with the following structure:

myapp/
    __init__.py
    admin.py
    apps.py
    models.py
    tests.py
    views.py

Registering the App

Add the new app to the INSTALLED_APPS list in settings.py:

INSTALLED_APPS = [
    ...
    'myapp',
]

  1. Django Models, Views, and Templates (MVT)

Models

Define your data models in models.py:

from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name

Run the following commands to create the database tables:

python manage.py makemigrations
python manage.py migrate

Views

Define your views in views.py:

from django.shortcuts import render
from .models import Item

def item_list(request):
    items = Item.objects.all()
    return render(request, 'item_list.html', {'items': items})

Templates

Create a directory named templates inside your app directory and add an HTML file item_list.html:

<!DOCTYPE html>
<html>
<head>
    <title>Item List</title>
</head>
<body>
    <h1>Items</h1>
    <ul>
        {% for item in items %}
            <li>{{ item.name }}: {{ item.description }}</li>
        {% endfor %}
    </ul>
</body>
</html>

URL Routing

Define the URL pattern for your view in urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('items/', views.item_list, name='item_list'),
]

Include the app's URL patterns in the project's urls.py:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]

  1. Admin Interface

Django provides a built-in admin interface to manage your models. Register your models in admin.py:

from django.contrib import admin
from .models import Item

admin.site.register(Item)

Run the development server:

python manage.py runserver

Access the admin interface at http://127.0.0.1:8000/admin/ and log in with the superuser credentials.

  1. URL Routing

Django uses URL routing to map URLs to views. The urls.py file in your project and app directories define these mappings.

Example

from django.urls import path
from . import views

urlpatterns = [
    path('items/', views.item_list, name='item_list'),
]

Conclusion

In this section, we covered the basics of Django, including setting up a project, understanding its structure, and creating a simple web application. We also explored the MVT pattern, URL routing, and the admin interface. In the next section, we will dive deeper into building more complex web applications using Django.

Python Programming Course

Module 1: Introduction to Python

Module 2: Control Structures

Module 3: Functions and Modules

Module 4: Data Structures

Module 5: Object-Oriented Programming

Module 6: File Handling

Module 7: Error Handling and Exceptions

Module 8: Advanced Topics

Module 9: Testing and Debugging

Module 10: Web Development with Python

Module 11: Data Science with Python

Module 12: Final Project

© Copyright 2024. All rights reserved