Updat Notes

  • 2018-01-24: Django 1.1.4
  • 2019-09-17: Django 2.2.2
  • 2020-07-28: Django 3.1.1

About Django

Django is an extremely popular and fully featured server-side web framework, written in Python languages,which was invented to meet fast-moving newsroom deadlines, while satisfying the tough requirements of experienced Web developers.

Django Environment

As we only need Django itself on my computer to develop, so I don’t need to create any virtual environment, but in in production environment, it is very necessary to set up a virtual env to avoid the problems.

1
2
3
$ python --version
Python 3.8.3
$ pip3 install --upgrade django
1
2
3
4
5
6
7
8
$ G:\Python\Django\demo
>>> import django
>>> django.get_version()
'3.1.1'
$ G:\Python\Django\demo\>django-admin --version
3.1.1
$ G:\Python\Django\demo\>py -m django --version
3.1.1
1
2
3
$ django-admin startproject myproject
$ cd myproject
$ python manage.py runserver

Then, visit http://127.0.0.1:8000/ with your familiar Web browser. You’ll see a “Congratulations!” page, with a rocket taking off.

It worked!

Introduction

Let’s look at what yourproject created first:

1
2
3
4
5
6
7
yourproject/
manage.py
yourproject/
__init__.py
settings.py
urls.py
wsgi.py

These files are:

  • The outer yourproject root directory is just a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.

  • manage.py: A command-line utility(命令行工具) that lets you interact with Django project in various ways.

  • The inner yourproject directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it .

  • yourproject/__init__.py: An empty file that tells Python that this directory should be considered a Python package.

  • yourproject/settings.py: Settings/configuration for Django project,. this is where we register any applications we create, the location of our static files, database configuration details, etc.

  • yourproject/urls.py: The URL declarations for this Django project.

  • yourproject/wsgi.py: An entry-point for WSGI(Web Server Gateway Interface)-compatible web servers.

  • yourproject/asgi.py: An entry-point for ASGI-compatible web servers to serve your project.

    You can treat this as boilerplate.

Let us run it on your computer:

By default, the server runs on port 8000 on the IP address 127.0.0.1 OR localhost. You can pass in an IP address and port number explicitly.

1
$ python manage.py runserver 8080 ## it starts the server on port 8080

To make your development server viewable to other machines on the network, use its own IP address (e.g. 192.168.2.1) or 0.0.0.0 or :: (with IPv6 enabled) with --settings=yourproject.settings.

1
2
3
$ python manage.py runserver 0:8000 ## 0 is a shortcut for 0.0.0.0. 
$ python manage.py runserver 192.168.2.1:8000
$ python manage.py runserver 127.0.0.1:8001 --settings=yourproject.settings

Automatic reloading of runserver

The development server automatically reloads Python code for each request as needed. You don’t need to restart the server for code changes to take effect.

However, some actions like adding files don’t trigger a restart, so you’ll have to restart the server in these cases.

https://docs.djangoproject.com/en/3.1/ref/django-admin/#runserver

Create your first APP

To create your app, make sure you’re in the same directory as manage.py :

1
$ python manage.py startapp apps

That’ll create a directory apps, which is laid out like this:

1
2
3
4
5
6
7
8
9
apps/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py

In addition we now have:

  • A migrations folder, used to store “migrations” — files that allow you to automatically update your database as you modify your models.
  • _init_.py — a python Package file.

Django web applications typically group the code that handles each of these steps into separate files,

The following diagram describes the main data flow, and the components required when handling HTTP requests and responses. As we already implemented the model, the main components we’ll create are:

  • URL mappers to forward the supported URLs (and any information encoded in the URLs) to the appropriate view functions.
  • View functions to get the requested data from the models, create HTML pages that display the data, and return the pages to the user to view in the browser.
  • Templates to use when rendering data in the views.

img

Note

A website may consist of one or more sections, e.g. main site, blog, wiki, downloads area, etc. Django encourages you to develop these components as separate applications, which could then be re-used in different projects if desired.

Write your first view

Let’s write the first view. Open the file apps/views.py and put the following Python code in it:

1
2
3
4
from django.http import HttpResponse

def index(request):
return HttpResponse("Hello, World!")

This is the simplest view maybe in Django.

To call the view, we need to map it to a URL - and for this we need a URLconf.

In the apps/urls.py file include the following code:

1
2
3
4
5
6
7
from django.urls import path

from . import views

urlpatterns = [
path('', views.index, name='index'),
]

The next step is to point the root URLconf at the apps.urls module.

In yourproject/urls.py, add an import from django.contrib and insert an include()in the urlpatternslist, so you have:

1
2
3
4
5
6
7
from django.contrib import admin
from django.urls import include, path

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

The include() function allows referencing other URLconfs, make it easy to plug-and-play URLs.

Since apps are in their own URLconf (apps/urls.py), they can be placed under “/apps/”, or under “/movies/apps/”, or any other path root, and the app will still work.

Go to http://localhost:8080/apps/ in your browser, and you should see the text , which you defined in the index view.

But http://localhost:8080/ will not work since you don’t add the URLconf , if you write the path('', include('apps.urls')), then the text will be displayed, OR you can use a special view function RedirectViews ,e.g. RedirectView.as_view(url='/apps/', permanent=True) in yourproject/urls.py to redirect the root URL:

1
2
3
4
5
6
7
8
9
10
# Add URL maps to redirect the base URL to our application
from django.views.generic import RedirectView
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
path('',RedirectView.as_view(url='/apps/', permanent=True)),
path('apps/', include('apps.urls')),
path('admin/', admin.site.urls),
]

Django does not serve static files like CSS, JavaScript, and images by default, but it can be useful for the development web server to do so while you’re creating your site.

As a final addition to this URL mapper, you can enable the serving of static files during development by appending the following lines.

Add the following final block to the bottom of the file now in yourproject/urls.py:

1
2
3
4
5
6
7
8
9
10
11
12
## Add URL maps to redirect the base URL to our application
from django.views.generic import RedirectView
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
path('',RedirectView.as_view(url='/apps/', permanent=True)),
path('apps/', include('apps.urls')),
path('admin/', admin.site.urls),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Settings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import os
import datetime

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'xc3=e7kw8lr+pbjo+3g_x++hs4n3rij2=$s=ygu$+$9fp!@^t2'

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

# When yourproject is developed locally, no setting is required.
ALLOWED_HOSTS = []
# When your projcet is exposed to internet, thatis the Hostname/IP address available for accessing the django project.
ALLOWED_HOSTS = ["localhost","192.168.10.*","127.0.0.1"]

To include the app in our project or registered, we need to add a reference to its configuration class in the INSTALLED_APPSsetting. The appsConfig class is in the apps/apps.py file, so its dotted path is 'apps.apps.appsConfig' OR just apps(Not recommended). Edit the yourproject/settings.py file and add that dotted path to the INSTALLED_APPSIt’ll look like this:

1
2
3
4
5
6
7
8
9
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.apps.appsConfig',
]

By default, INSTALLED_APPS contains the following apps, all of which come with Django:

  • django.contrib.admin – The admin site. You’ll use it shortly.
  • django.contrib.auth – An authentication system.
  • django.contrib.contenttypes – A framework for content types.
  • django.contrib.sessions – A session framework.
  • django.contrib.messages – A messaging framework.
  • django.contrib.staticfiles – A framework for managing static files.

While you’re editing yourproject/settings.py, set TIME_ZONE to your local time zone , for example, set the TIME_ZONE = 'Asia/Shanghai'. And if you don’t know the format , you can check the timezone standard tz name from wikipedia(List of tz database time zones) here.

Here we can set static and media path:

1
2
3
4
5
6
7
STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, "static")

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'

REFERENCES