Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Django: Creating Your First Project

Django: Creating Your First Project

In this chapter we will introduce the Django management tool and how to use Django to create a project; for the first project we name it HelloWorld.

Test version description:

You can view the version number with the following command:

# python3 -V

Python 3.9.7

# python3 -m django --version

4.2.7


Django management tool

After installing Django, you should now have the available management tool django-admin; on Windows, if environment variables are not configured, you can use django-admin.

Let's take a look at the django-admin command introduction:



$ django-admin



Type 'django-admin help ' for help on a specific subcommand.



Available subcommands:



[django]

    check

    compilemessages

    createcachetable

    dbshell

    diffsettings

    dumpdata

    flush

    inspectdb

    loaddata

    makemessages

    makemigrations

    migrate

    runserver

    sendtestemail

    shell

    showmigrations

    sqlflush

    sqlmigrate

    sqlsequencereset

    squashmigrations

    startapp

    startproject

    test

    testserver

……省略部分……


Create your first project

Use django-admin to create the HelloWorld project:



django-admin startproject HelloWorld

After creation, we can view the project's directory structure:



$ cd HelloWorld/

$ tree

HelloWorld/                  # 项目根目录

├── manage.py                # 项目管理脚本

├── db.sqlite3               # SQLite 数据库文件

├── __pycache__/             # Python 字节码缓存

└── HelloWorld/              # 项目配置目录(与项目同名)

    ├── __init__.py          # 包标识文件

    ├── settings.py          # 项目设置

    ├── urls.py             # 主路由配置

    ├── asgi.py             # ASGI 配置

    └── wsgi.py             # WSGI 配置

** Project root directory (HelloWorld/):**

File/Directory Purpose
manage.py Django command-line tool entry point, used for running the development server, database migrations, and other operations.
db.sqlite3 SQLite database file (default database, used in development environments).
__pycache__/ Python bytecode cache directory (generated automatically, no manual modification needed).

** Main project configuration directory (HelloWorld/HelloWorld/):**

File/Directory Purpose
__init__.py Empty file that tells Python this directory is a package.
settings.py Core configuration file, containing:
 - 数据库设置 (`DATABASES`)       

 - 静态文件路径 (`STATIC_URL`)       

 - 应用注册 (`INSTALLED_APPS`)       

 - 调试模式 (`DEBUG=True/False`) |

| urls.py | Main routing configuration file, defines the mapping between URL paths and views. | | asgi.py | ASGI server configuration (for asynchronous web servers such as Daphne). | | wsgi.py | WSGI server configuration (for traditional web servers such as Gunicorn, uWSGI). |

Next, we enter the HelloWorld directory and enter 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, 8000 is the port number. If not specified, the port number defaults to 8000.

Enter your server's IP in the browser (here we enter the local IP address: 127.0.0.1:8000) and port number. If it starts normally, the output is as follows:

Key files explained in detail

1. settings.py (core configuration)

Example

HelloWorld/settings.py example snippet

Security warning: DEBUG must be turned off in production!

DEBUG

=

True

Allowed hostnames (must be configured when DEBUG=False)

ALLOWED_HOSTS

=

[

]

Registered Django applications

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 (SQLite by default)

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)

Example

HelloWorld/urls.py example

from

django.

contrib

import

admin

from

django.

urls

import

path

urlpatterns

=

[

    path

(

'admin/'

,

admin.

site

.

urls

)

,

 

Admin routing

   

You can add custom routes here, such as:

   

path('blog/', include('blog.urls')),

]

** 3. manage.py (project management script)**

Example

#!/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 directory inside the previously created HelloWorld directory, and enter the 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 the urls.py file, delete the original code, and copy and paste the following code into the urls.py file:

HelloWorld/HelloWorld/urls.py file code:

from

django

.

urls

import

path

from

.

import

views

urlpatterns

=

[

path

(

"

"

,

views

.

hello

,

name

=

"

hello

"

)

,

]

The entire directory structure is as follows:



$ tree

.

|-- HelloWorld

|   |-- __init__.py

|   |-- __init__.pyc

|   |-- settings.py

|   |-- settings.pyc

|   |-- urls.py              # url 配置

|   |-- urls.pyc

|   |-- views.py              # 添加的视图文件

|   |-- views.pyc             # 编译后的视图文件

|   |-- wsgi.py

|   `-- wsgi.pyc

`-- manage.py

Once done, start the Django development server and open a browser to visit:

We can also modify the following rules:

HelloWorld/HelloWorld/urls.py file code:

from

django

.

urls

import

path

from

.

import

views

urlpatterns

=

[

path

(

'

hello/

'

,

views

.

hello

)

,

]

Open through the browser http://127.0.0.1:8000/hello, the output is as follows:

**Note:** If the code in the project changes, the server automatically detects the changes and reloads, so if you have already started the server, there is no need to restart it manually.


path() function

Django path() can accept four parameters: two required parameters, route and view, and two optional parameters, kwargs and name.

Syntax format:

path(route, view, kwargs=None, name=None)

In Django 2.0, the re_path() method can be used to be compatible with the url() method in version 1.x; some regular expression rules can also be implemented through re_path().

from django.urls import include, re_path



urlpatterns = [

    re_path(r'^index/$', views.index, name='index'),

    re_path(r'^bio/(?P\w+)/$', views.bio, name='bio'),

    re_path(r'^weblog/', include('blog.urls')),

    ...

]