Django Create First Project | Novice Tutorial
This chapter will introduce Django's management tools and how to use Django to create a project. For our first project, we'll name it HelloWorld.
Test version specifications:
- Python 3.9.7
- Django 4.2.7
Check version numbers with the following commands:
# python3 -V
Python 3.9.7
# python3 -m django --version
4.2.7
Django Management Tools
After installing Django, you should now have access to the management tool django-admin. On Windows, you can use django-admin if environment variables are configured.
Let's look at the command overview of django-admin:
$ django-admin
Type 'django-admin help <subcommand>' for help on a specific subcommand.
Available subcommands:
check
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
makemigrations
migrate
runserver
sendtestemail
shell
showmigrations
sqlflush
sqlmigrate
sqlsequencereset
squashmigrations
startapp
startproject
test
testserver
...(partial content omitted)...
Creating the First Project
Use django-admin to create the HelloWorld project:
django-admin startproject HelloWorld
After creation, let's examine the project directory structure:
$ cd HelloWorld/
$ tree
HelloWorld/ # Project root directory
βββ manage.py # Project management script
βββ db.sqlite3 # SQLite database file
βββ __pycache__/ # Python bytecode cache
βββ HelloWorld/ # Project config directory (same name as project)
βββ __init__.py # Package identifier file
βββ settings.py # Project settings
βββ urls.py # Main routing configuration
βββ asgi.py # ASGI configuration
βββ wsgi.py # WSGI configuration
Project Root Directory (HelloWorld/):
| File/Directory | Purpose |
|---|---|
manage.py |
Django command-line tool entry point for running development server, database migrations, etc. |
db.sqlite3 |
SQLite database file (default database for development environment). |
__pycache__/ |
Python bytecode cache directory (auto-generated, no manual modification needed). |
Main Project Config Directory (HelloWorld/HelloWorld/):
| File/Directory | Purpose |
|---|---|
__init__.py |
Empty file that tells Python this directory is a package. |
settings.py |
Core configuration file containing:
|
urls.py |
Main routing configuration file defining URL path to view mappings. |
asgi.py |
ASGI server configuration (for async web servers like Daphne). |
wsgi.py |
WSGI server configuration (for traditional web servers like Gunicorn, uWSGI). |
Next, enter the HelloWorld directory and run the following command to start the server:
python3 manage.py runserver 0.0.0.0:8000
0.0.0.0 allows other computers to connect to the development server, while 8000 is the port number. If unspecified, the default port is 8000.
Enter your server's IP (here we'll use localhost: 127.0.0.1:8000) and port number in your browser. If started successfully, you'll see:
Key File Details
1. settings.py (Core Configuration)
# HelloWorld/settings.py example snippet
# Security warning: DEBUG must be disabled in production!
DEBUG = True
# Allowed hostnames (required when DEBUG=False)
ALLOWED_HOSTS = []
# Registered Django apps
INSTALLED_APPS = [
'django.contrib.admin', # Admin backend
'django.contrib.auth', # Authentication system
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles', # Static file handling
]
# Database configuration (default SQLite)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3', # Database file path
}
}
# Static file URL (CSS/JS/images)
STATIC_URL = 'static/'
2. urls.py (Routing Configuration)
# HelloWorld/urls.py example
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls), # Admin backend route
# Add custom routes here, e.g.:
# path('blog/', include('blog.urls')),
]
3. manage.py (Project Management Script)
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "HelloWorld.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
Views and URL Configuration
Create a new views.py file in the HelloWorld/HelloWorld directory and add the following code:
# HelloWorld/HelloWorld/views.py file code:
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world ! ")
Next, bind the URL to the view function. Open urls.py, replace the existing code with:
# HelloWorld/HelloWorld/urls.py file code:
from django.urls import path
from . import views
urlpatterns = [
path("", views.hello, name="hello"),
]
The complete directory structure now looks like:
$ tree
.
|-- HelloWorld
| |-- __init__.py
| |-- __init__.pyc
| |-- settings.py
| |-- settings.pyc
| |-- urls.py # url configuration
| |-- urls.pyc
| |-- views.py # Added view file
| |-- views.pyc # Compiled view file
| |-- wsgi.py
| `-- wsgi.pyc
`-- manage.py
After completion, start the Django development server and access it in your browser:
We can also modify the routing rules:
# HelloWorld/HelloWorld/urls.py file code:
from django.urls import path
from . import views
urlpatterns = [
path('hello/', views.hello),
]
Access http://127.0.0.1:8000/hello in your browser to see:
Note: The server automatically detects code changes and reloads, so you don't need to manually restart if you've already started the server.
path() Function
Django's path() accepts four parameters: two required (route, view) and two optional (kwargs, name).
Syntax:
path(route, view, kwargs=None, name=None)
- route: String defining the URL path. Can include variables like
<int:my_variable>to capture parameters from the URL and pass them to the view function. - view: View function that handles requests matching the given route. Can be a function or class-based view.
- kwargs (optional): Dictionary containing additional keyword arguments to pass to the view function.
- name (optional): Unique name for the URL route, allowing references elsewhere in code. Useful for generating URLs in templates or redirects.
Django 2.0 can use re_path() to maintain compatibility with Django 1.x's url() method. Regular expression rules can also be implemented with re_path().
from django.urls import include, re_path
urlpatterns = [
re_path(r'^index/$', views.index, name='index'),
re_path(r'^bio/(?P<username>w+)/$', views.bio, name='bio'),
re_path(r'^weblog/', include('blog.urls')),
...
]
YouTip