Introduction to Django

Loading

Django is a high-level Python web framework that enables rapid development of secure and scalable web applications. It follows the Model-View-Template (MVT) architecture and is known for its “batteries-included” approach, providing built-in features like authentication, database management, and an admin panel.


Why Use Django?

  • Fast Development: Django’s structure allows developers to build applications quickly.
  • Secure: Protects against security threats like SQL injection and XSS.
  • Scalable: Suitable for both small projects and large-scale applications.
  • ORM (Object-Relational Mapping): Simplifies database operations.
  • Built-in Admin Panel: Auto-generates a dashboard for managing data.
  • RESTful API Support: Easily integrate Django with REST frameworks.

Installing Django

To install Django, use:

pip install django

Verify the installation:

django-admin --version

Creating a Django Project

Step 1: Start a New Project

Run:

django-admin startproject myproject

This creates the following structure:

myproject/
│── manage.py
│── myproject/
│── __init__.py
│── settings.py
│── urls.py
│── wsgi.py

Step 2: Running the Development Server

Navigate into the project folder and run:

python manage.py runserver

Visit http://127.0.0.1:8000/ in a browser to see Django’s welcome page.


Understanding Django’s MVT Architecture

1. Model (M) – Database Layer

Defines the structure of data using Django’s ORM.

Example:

from django.db import models

class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=100)
published_date = models.DateField()

2. View (V) – Business Logic

Handles user requests and returns a response.

Example:

from django.http import HttpResponse

def home(request):
return HttpResponse("Welcome to Django!")

3. Template (T) – Presentation Layer

Django templates contain HTML with dynamic data.

Example index.html:

<!DOCTYPE html>
<html>
<head>
<title>My Django App</title>
</head>
<body>
<h1>Welcome to My Django App</h1>
</body>
</html>

Creating a Django App

Step 1: Create an App

python manage.py startapp myapp

This generates:

myapp/
│── models.py
│── views.py
│── urls.py
│── templates/
│── static/

Step 2: Define a View

Edit views.py:

from django.shortcuts import render

def home(request):
return render(request, 'index.html')

Step 3: Configure URLs

Edit urls.py in the project folder:

from django.urls import path
from myapp import views

urlpatterns = [
path('', views.home, name='home'),
]

Django ORM (Database Handling)

Step 1: Configure Database

In settings.py, configure:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / "db.sqlite3",
}
}

Step 2: Create Models

Edit models.py:

from django.db import models

class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()

Step 3: Apply Migrations

python manage.py makemigrations
python manage.py migrate

Django Admin Panel

Step 1: Create a Superuser

python manage.py createsuperuser

Follow the prompts to set a username and password.

Step 2: Register Models in Admin Panel

Edit admin.py:

from django.contrib import admin
from .models import Student

admin.site.register(Student)

Now, access http://127.0.0.1:8000/admin/ and log in.


Working with Forms in Django

Step 1: Create a Django Form

Edit forms.py:

from django import forms

class StudentForm(forms.Form):
name = forms.CharField(label='Name', max_length=100)
age = forms.IntegerField(label='Age')

Step 2: Handle Form Submission

Edit views.py:

from django.shortcuts import render
from .forms import StudentForm

def student_form(request):
form = StudentForm()
return render(request, 'student_form.html', {'form': form})

Step 3: Create a Template

Create student_form.html:

<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>

Building a REST API with Django Rest Framework (DRF)

Step 1: Install DRF

pip install djangorestframework

Step 2: Update settings.py

INSTALLED_APPS = [
'rest_framework',
'myapp',
]

Step 3: Create a Serializer

Edit serializers.py:

from rest_framework import serializers
from .models import Student

class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = '__all__'

Step 4: Create an API View

Edit views.py:

from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Student
from .serializers import StudentSerializer

@api_view(['GET'])
def student_list(request):
students = Student.objects.all()
serializer = StudentSerializer(students, many=True)
return Response(serializer.data)

Step 5: Configure URLs

Edit urls.py:

from django.urls import path
from .views import student_list

urlpatterns = [
path('api/students/', student_list),
]

Now, visiting http://127.0.0.1:8000/api/students/ returns JSON data.


Deploying Django Applications

  1. Use Gunicorn for Production bashCopyEditpip install gunicorn gunicorn myproject.wsgi
  2. Deploy on Heroku, AWS, or DigitalOcean.
  3. Use Docker for containerization.

Leave a Reply

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