Creating a Django App

A Django app is a self-contained module that handles a specific functionality within a project. When you create an app using:

python manage.py startapp blog

Django generates the following structure:

blog/
│
├── migrations/
│   └── __init__.py
│
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
├── views.py
└── urls.py (created manually)

__init__.py

This file tells Python that the directory should be treated as a Python package.

admin.py

Used to register models with Django’s admin panel so they can be managed through the built-in administration interface.

Example:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

apps.py

Contains the app configuration and metadata.

Example:

from django.apps import AppConfig

class BlogConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'blog'

models.py

Defines the database tables and relationships using Django models.

Example:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

views.py

Contains the business logic and handles user requests.

Example:

from django.http import HttpResponse

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

tests.py

Used to write test cases for the application.

Example:

from django.test import TestCase

migrations/

Stores migration files that track database schema changes.

Example migration command:

python manage.py makemigrations
python manage.py migrate

urls.py

This file is not created by default and is usually added manually to define app-specific URLs.

Example:

from django.urls import path
from .views import home

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

The app structure helps organize code into separate modules, making Django projects easier to maintain, scale, and reuse.