WikiGalaxy

Personalize

Django MVC Architecture

Understanding Django MVC Architecture

Django follows the Model-View-Controller (MVC) architecture pattern, which helps in organizing code efficiently by separating concerns. In Django, it's referred to as the Model-View-Template (MVT) pattern due to its template system.

  • Model
  • The Model is the data access layer. It defines the data structure and handles the database interactions.

  • View
  • The View is the business logic layer. It processes requests and returns responses.

  • Template
  • The Template is the presentation layer. It is responsible for rendering HTML content.

Model Example: Defining a Simple Model

Defining a Simple Model

In Django, models are defined as Python classes and mapped to database tables.


from django.db import models

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

Explanation

The above example demonstrates a simple model named `Book` with fields for `title`, `author`, and `published_date`. Each field corresponds to a column in the database table.

View Example: Creating a Simple View

Creating a Simple View

Views in Django handle requests and return responses. They can render templates or return JSON data.


from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world!")
    

Explanation

This simple view function returns a plain text response "Hello, world!" when accessed. It's a basic example of how views can be used to handle HTTP requests in Django.

Template Example: Rendering a Template

Rendering a Template

Templates are used to render HTML content dynamically, using context data passed from views.


from django.shortcuts import render

def homepage(request):
    return render(request, 'home.html', {'title': 'Home Page'})
    

Explanation

In this example, the `homepage` view renders the `home.html` template and passes a context dictionary containing a `title` key. The template can use this context to display dynamic content.

URL Routing Example

URL Routing

URL routing in Django is handled by the `urls.py` file, which maps URLs to views.


from django.urls import path
from . import views

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

Explanation

This example shows how to map the root URL (`''`) to the `index` view function. The `urlpatterns` list is used to define URL patterns and their corresponding views.

Form Handling Example

Form Handling

Django provides a powerful form handling mechanism to process user input safely and efficiently.


from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)
    

Explanation

The `ContactForm` class defines a form with `name`, `email`, and `message` fields. Django's form handling ensures that the input is validated and sanitized before processing.

Admin Interface Example

Admin Interface

Django provides a built-in admin interface for managing models and data.


from django.contrib import admin
from .models import Book

admin.site.register(Book)
    

Explanation

By registering the `Book` model with the admin site, you can manage books through Django's admin interface. This feature is extremely useful for quickly managing application data during development.

Middleware Example

Middleware

Middleware in Django is a way to process requests globally before they reach the view.


class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response
    

Explanation

This example demonstrates a simple middleware class that processes a request and then passes it to the next middleware or view. Middleware can modify requests and responses, making it a powerful tool for cross-cutting concerns.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025