Exploring Project Structure - potatoscript/django GitHub Wiki

πŸ—οΈ Django Project Structure Overview

When you start a new Django project using the command django-admin startproject mysite, Django automatically creates a set of files and directories for you. Here's a breakdown of the default structure:

Default Project Structure

mysite/
β”‚
β”œβ”€β”€ mysite/                   # The inner folder containing the core project files
β”‚   β”œβ”€β”€ __init__.py            # Empty file that tells Python this is a package
β”‚   β”œβ”€β”€ settings.py            # Project settings: language, database, etc.
β”‚   β”œβ”€β”€ urls.py                # The URL dispatcher for the project
β”‚   β”œβ”€β”€ asgi.py                # ASGI application setup (for asynchronous support)
β”‚   β”œβ”€β”€ wsgi.py                # WSGI application setup (for synchronous support)
β”‚
β”œβ”€β”€ manage.py                  # The script used to manage the project (start server, migrate, etc.)
β”‚
└── hello/                     # Your app folder (created by `startapp`)
    β”œβ”€β”€ __init__.py            # Makes this folder a Python package
    β”œβ”€β”€ admin.py               # Admin panel configurations for this app
    β”œβ”€β”€ apps.py                # App configuration
    β”œβ”€β”€ migrations/            # Database migrations (like a history of schema changes)
    β”œβ”€β”€ models.py              # Database models for your app
    β”œβ”€β”€ tests.py               # Tests for your app
    β”œβ”€β”€ views.py               # Views or functions that handle HTTP requests
    └── urls.py                # URL patterns specific to this app

πŸ§‘β€πŸ’» Let's Break Down Each File & Folder

1. mysite/manage.py (The Project's Remote Control)

This is your main control script. Think of it like a remote to manage your Django project. You'll use it to do tasks like running the development server, running database migrations, creating apps, and more.

  • Command Examples:
    • Start the development server:
      python manage.py runserver
      
    • Create a new app:
      python manage.py startapp myapp
      
    • Run migrations to update the database:
      python manage.py migrate
      

2. mysite/ (The Inner Project Folder)

This folder contains your core project files. These files are used for configuring settings and routing. Let's explore them one by one:

πŸ› οΈ mysite/settings.py

This file contains all the settings that tell Django how to behave.

  • Secret Key:
    Django uses a secret key for security purposes. You should never share this key publicly.
SECRET_KEY = 'your-secret-key-here'
  • Installed Apps:
    This is a list of all the apps that are part of your project. These include both built-in Django apps (like django.contrib.admin) and apps you create yourself (like hello).
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello',  # This is our app
]
  • Database Configuration:
    Django uses a database to store your data (like blog posts, user accounts, etc.). By default, it uses SQLite, a simple database file.
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / "db.sqlite3",
    }
}
  • Static and Media Files:
    Django helps you manage your static files (like CSS, JavaScript) and media files (like images or user uploads).
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

🌐 mysite/urls.py (Routing URLs)

This file defines the URLs (paths) of your website and connects them to views that return the content.

  1. Default Project URLs:
    It includes the Django admin panel and points the root of the website (/) to an app (we'll set this up next).
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),  # Admin Panel
    path('', include('hello.urls')),  # Link to our 'hello' app
]
  1. Example URL Routing:
    • path('admin/', admin.site.urls) β€” This is the URL for the Django admin panel.
    • path('', include('hello.urls')) β€” This links to the hello app’s URL configuration.

3. App Folder: hello/ (Your First App)

When you run the command python manage.py startapp hello, Django creates the hello app folder, which will contain all your business logic, models, views, and more.

πŸ”§ hello/models.py (Database Models)

Models are like blueprints for your data. They define the structure of the database tables that hold your data.

Example:

Let’s say you want to store information about blog posts. You can create a Post model:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)  # Title of the post
    content = models.TextField()  # The content of the post
    created_at = models.DateTimeField(auto_now_add=True)  # Automatically set the date when post is created

    def __str__(self):
        return self.title
  • Field Types:
    • CharField is used for short text (like titles).
    • TextField is used for long text (like the content of a blog post).
    • DateTimeField is used to store date and time values.

πŸ“ hello/views.py (Handling User Requests)

In Django, views are the functions that handle user requests and return responses. Views take a request, perform actions (like querying the database), and then return an HTTP response.

Here’s an example of a simple view that shows a greeting:

from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello, welcome to my Django website!")
  • Request: The data Django receives when someone visits your website.
  • HttpResponse: The data Django sends back to the user’s browser.

πŸ› οΈ hello/urls.py (App-specific URL Routing)

Each app can have its own urls.py file to define URLs specific to that app. For example, in our hello/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home),  # This URL connects to the 'home' view
]
  • path('', views.home) means that when someone visits the home page, Django will use the home() function from views.py to respond.

πŸ§ͺ hello/tests.py (Testing Your Code)

Django encourages you to write tests to ensure your code works as expected. This file is where you can add tests for your models, views, or any part of the application.

For example, let's test if the home() view returns the correct response:

from django.test import TestCase
from django.urls import reverse

class HomeViewTests(TestCase):
    def test_home_view(self):
        response = self.client.get(reverse('home'))  # Simulate a GET request to the home page
        self.assertEqual(response.status_code, 200)  # Assert that the status code is 200 (OK)
        self.assertContains(response, "Hello, welcome to my Django website!")  # Assert that the response contains this text

4. hello/admin.py (Admin Panel Configuration)

The admin panel is a great tool that allows you to manage your app’s data. You can add, edit, and delete data from the database without writing any code.

To use the admin panel, you need to register your models:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

Now, you can go to http://127.0.0.1:8000/admin/, log in, and manage Post objects from the browser.


πŸŽ“ Understanding Django’s Workflow

Here’s a simple flow of how a request works in Django:

  1. Request: The user enters http://127.0.0.1:8000/ in their browser.
  2. URL Routing: Django looks at the urls.py file to find which view to call.
  3. View: The home() view is executed, and it sends an HTTP response back to the browser.
  4. Response: The browser shows the "Hello, welcome to my Django website!" message.