Creating Your First Django Project
Django provides the django-admin command-line tool to create new projects with a proper directory structure. A Django project is a collection of settings, configurations, and apps that together form a web application.
Creating a Project
Use django-admin startproject to scaffold a new project. This creates a directory with manage.py (the project's command-line utility) and an inner project directory containing settings, URLs, and WSGI/ASGI configuration files.
QuerySets are LAZY — no DB hit until evaluated.
Project Creation Steps
- Run: django-admin startproject mysite
- This creates: mysite/ (outer) and mysite/mysite/ (inner)
- manage.py — Command-line utility for the project
- settings.py — All project configuration
- urls.py — URL declarations (the 'table of contents')
- wsgi.py — WSGI entry point for deployment
- asgi.py — ASGI entry point for async deployment
Create & Explore Project
# Create a new Django project
# django-admin startproject mysite
# Project structure:
# mysite/
# manage.py <- Command-line utility
# mysite/
# __init__.py <- Python package marker
# settings.py <- Project settings
# urls.py <- URL routing
# wsgi.py <- WSGI config (deployment)
# asgi.py <- ASGI config (async)
# Navigate into the project
# cd mysite
# Run the development server
# python manage.py runserver
# Visit: http://127.0.0.1:8000/
# You should see the Django welcome page!Tip
Tip
Use path() for clean URLs and include() to modularize app URLs. Always name your URL patterns for use with {% url %} template tag.
Common Mistake
Warning
Hardcoding URLs in templates like <a href='/blog/1/'> breaks when URLs change. Always use {% url 'post_detail' pk=1 %} instead.
Practice Task
Note
(1) Create a URL pattern with a dynamic parameter. (2) Use include() to add app URLs. (3) Name all your URL patterns.
Quick Quiz
Key Takeaways
- Django provides the django-admin command-line tool to create new projects with a proper directory structure.
- Run: django-admin startproject mysite
- This creates: mysite/ (outer) and mysite/mysite/ (inner)
- manage.py — Command-line utility for the project