Skip to content

Chapter 1: First Look at Django

1.3 First Django Project

Create Project: django-admin startproject

Make sure virtual environment is activated, then create your first Django project.

Basic Project Creation

bash
# Create Django project named mysite
django-admin startproject mysite

# Enter project directory
cd mysite

# View project structure
tree mysite  # Windows/Linux
# or
ls -la       # View file list

Project Creation Best Practices

Recommended project creation way, avoid nested directories:

bash
# Create project in current directory (note the dot at end)
django-admin startproject mysite .

# Or specify project directory
mkdir my_django_project
cd my_django_project
django-admin startproject mysite

Project Structure Analysis

After creating project, you will see this directory structure:

mysite/
├── manage.py
└── mysite/
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    ├── wsgi.py
    └── asgi.py

Let's understand each file's function:

manage.py

Project management script, used to execute various Django commands. Common manage.py commands:

bash
python manage.py runserver      # Start development server
python manage.py migrate        # Execute database migrations
python manage.py createsuperuser # Create superuser
python manage.py shell          # Start Django shell
python manage.py collectstatic  # Collect static files

mysite/__init__.py

Empty file, tells Python this is a package directory. In Django 5.x usually kept empty.

mysite/settings.py

Project's core configuration file:

python
 
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-your-secret-key-here'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

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

# Password validation
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
STATIC_URL = 'static/'

# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Main configuration items:

  • SECRET_KEY: Key for encryption, must keep secret in production
  • DEBUG: Debug mode, must set to False in production
  • ALLOWED_HOSTS: List of allowed hosts
  • INSTALLED_APPS: List of installed apps
  • DATABASES: Database configuration
  • LANGUAGE_CODE: Language setting
  • TIME_ZONE: Timezone setting

mysite/urls.py

Main URL configuration file:

python
"""
URL configuration for mysite project.
"""
from django.contrib import admin
from django.urls import path

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

mysite/wsgi.py

WSGI (Web Server Gateway Interface) configuration, for deployment:

python
"""
WSGI config for mysite project.
"""

import os
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = get_wsgi_application()

mysite/asgi.py

ASGI (Asynchronous Server Gateway Interface) configuration, supports async and WebSocket:

python
"""
ASGI config for mysite project.
"""

import os
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = get_asgi_application()

Run Development Server

Start Server

bash
# Start development server (default port 8000)
python manage.py runserver
 
# Starting development server at http://127.0.0.1:8000/
# Quit the server with CONTROL-C.

Custom Port and IP

bash
# Specify port
python manage.py runserver 8080

# Specify IP and port
python manage.py runserver 0.0.0.0:8000

# Only listen to local loopback address
python manage.py runserver 127.0.0.1:8000

Access Website

Open browser, visit http://127.0.0.1:8000/, you will see Django welcome page:

The install worked successfully! Congratulations!

You are seeing this message because this Django installation is working correctly.

Hello World Example

Let's create a simple "Hello World" page.

1. Create View Function

Create views.py file in mysite/mysite/ directory:

python
# mysite/views.py
from django.http import HttpResponse
from django.shortcuts import render
import datetime

def hello_world(request):
    """Simple Hello World view"""
    return HttpResponse("Hello, World! Welcome to Django world!")

def hello_time(request):
    """View showing current time"""
    now = datetime.datetime.now()
    html = f"""
    <html>
    <head>
        <title>Django Hello World</title>
        <style>
            body {{ font-family: Arial, sans-serif; text-align: center; margin-top: 100px; }}
            h1 {{ color: #0c4b33; }}
            p {{ color: #666; font-size: 18px; }}
        </style>
    </head>
    <body>
        <h1>Hello, Django World!</h1>
        <p>Current time: {now.strftime('%Y-%m-%d %H:%M:%S')}</p>
        <p>This is your first Django page!</p>
    </body>
    </html>
    """
    return HttpResponse(html)

def hello_user(request):
    """Personalized greeting view"""
    user_name = request.GET.get('name', 'Visitor')
    return HttpResponse(f"<h1>Hello, {user_name}!</h1><p>Welcome to Django!</p>")

2. Configure URL Routing

Modify mysite/urls.py file:

python
# mysite/urls.py
from django.contrib import admin
from django.urls import path
from . import views  # Import our created views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.hello_world, name='hello_world'),           # Home page
    path('time/', views.hello_time, name='hello_time'),        # Time page
    path('user/', views.hello_user, name='hello_user'),        # User page
]

3. Test Pages

Restart development server (if already running, it will auto-reload):

bash
python manage.py runserver

Visit these URLs to test:

  • http://127.0.0.1:8000/ - Hello World page
  • http://127.0.0.1:8000/time/ - Show current time
  • http://127.0.0.1:8000/user/?name=John - Personalized greeting

4. Use Templates (Advanced Example)

Create template directory and files:

bash
# Create templates directory in project root
mkdir templates

Create hello.html in templates/ directory:

html
<!-- templates/hello.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Django Hello World</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            text-align: center;
            padding: 50px;
            margin: 0;
        }
        .container {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 15px;
            padding: 40px;
            max-width: 600px;
            margin: 0 auto;
            backdrop-filter: blur(10px);
        }
        h1 {
            font-size: 3em;
            margin-bottom: 20px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }
        p {
            font-size: 1.2em;
            line-height: 1.6;
        }
        .highlight {
            color: #ffd700;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎉 Hello, Django World!</h1>
        <p>Welcome to <span class="highlight">Django 5.x</span> world!</p>
        <p>Current time: <span class="highlight">{{ current_time }}</span></p>
        <p>Hello, <span class="highlight">{{ user_name }}</span>!</p>
        <p>This page is created using Django template system.</p>
    </div>
</body>
</html>

Update settings.py, configure template path:

python
# In settings.py find TEMPLATES configuration, modify DIRS
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],  # Add template directory
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Add view using template:

python
# Add in mysite/views.py
def hello_template(request):
    """View using template"""
    context = {
        'current_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'user_name': request.GET.get('name', 'Friend'),
    }
    return render(request, 'hello.html', context)

Update URL configuration:

python
# Add in mysite/urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.hello_world, name='hello_world'),
    path('time/', views.hello_time, name='hello_time'),
    path('user/', views.hello_user, name='hello_user'),
    path('template/', views.hello_template, name='hello_template'),  # New
]

Visit http://127.0.0.1:8000/template/?name=DjangoLearner to see effect.

Project Management Commands

Common Management Commands

bash
# Check project configuration
python manage.py check

# View all available commands
python manage.py help

# View help for specific command
python manage.py help runserver

# Start Django shell
python manage.py shell

# Collect static files
python manage.py collectstatic

# Create database migrations
python manage.py makemigrations

# Execute database migrations
python manage.py migrate

Test in Django shell

bash
python manage.py shell

In shell:

python
# Import Django settings
from django.conf import settings
print(settings.SECRET_KEY)

# Test views
from django.test import Client
client = Client()
response = client.get('/')
print(response.status_code)
print(response.content)

# View URL configuration
from django.urls import reverse
print(reverse('hello_world'))

Project Configuration Optimization

Chinese Localization Settings

Modify settings.py:

python
# Language setting
LANGUAGE_CODE = 'zh-hans'  # Simplified Chinese

# Timezone setting
TIME_ZONE = 'Asia/Shanghai'  # China timezone

# Internationalization
USE_I18N = True
USE_TZ = True

Development Environment Optimization

Add in settings.py:

python
# Development environment configuration
if DEBUG:
    # Allow all hosts (development only)
    ALLOWED_HOSTS = ['*']
    
    # Add debug toolbar (need separate installation)
    # pip install django-debug-toolbar
    # INSTALLED_APPS += ['debug_toolbar']
    # MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware']

Summary

Congratulations! You have successfully created and run your first Django project. In this section, you learned:

  1. ✅ Use django-admin startproject to create project
  2. ✅ Understand Django project directory structure
  3. ✅ Start development server
  4. ✅ Create simple views and URL configuration
  5. ✅ Use template system to create dynamic pages
  6. ✅ Basic project configuration and optimization

Key Concepts Review:

  • Project: Entire web application
  • View: Function that handles requests and returns responses
  • URL configuration: Maps URL paths to view functions
  • Template: Files used to generate HTML

Next Article

We will deeply learn Django core concept: MTV architecture pattern, and how to create and manage Django apps.

2.1 Django MTV Architecture Pattern →

Directory

Return to Course Directory

Released under the [BY-NC-ND License](https://creativecommons.org/licenses/by-nc-nd/4.0/deed.en).