DJango - Project Creation

Keywords: Programming Django Python Database MariaDB

Project creation

You need to select a directory as the project's home directory
You can have multiple apps in a project

Command help

Creating project methods

django-admin help startproject
usage: django-admin startproject [-h] [--version] [-v {0,1,2,3}]
                                 [--settings SETTINGS]
                                 [--pythonpath PYTHONPATH] [--traceback]
                                 [--no-color] [--template TEMPLATE]
                                 [--extension EXTENSIONS] [--name FILES]
                                 name [directory]

Creates a Django project directory structure for the given project name in the current directory or optionally in the given directory.

positional arguments:
  name                  Name of the application or project.
  directory             Optional destination directory

optional arguments:
  -h, --help            show this help message and exit
  --version             show program's version number and exit
  -v {0,1,2,3}, --verbosity {0,1,2,3}
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn't provided, the
                        DJANGO_SETTINGS_MODULE environment variable will be
                        used.
  --pythonpath PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Raise on CommandError exceptions
  --no-color            Don't colorize the command output.
  --template TEMPLATE   The path or URL to load the template from.
  --extension EXTENSIONS, -e EXTENSIONS
                        The file extension(s) to render (default: "py").
                        Separate multiple extensions with commas, or use -e
                        multiple times.
  --name FILES, -n FILES
                        The file name(s) to render. Separate multiple
                        extensions with commas, or use -n multiple times.

Creating apps methods

django-admin help startapp
usage: django-admin startapp [-h] [--version] [-v {0,1,2,3}]
                             [--settings SETTINGS] [--pythonpath PYTHONPATH]
                             [--traceback] [--no-color] [--template TEMPLATE]
                             [--extension EXTENSIONS] [--name FILES]
                             name [directory]

Creates a Django app directory structure for the given app name in the current directory or optionally in the given directory.

positional arguments:
  name                  Name of the application or project.
  directory             Optional destination directory

optional arguments:
  -h, --help            show this help message and exit
  --version             show program's version number and exit
  -v {0,1,2,3}, --verbosity {0,1,2,3}
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn't provided, the
                        DJANGO_SETTINGS_MODULE environment variable will be
                        used.
  --pythonpath PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Raise on CommandError exceptions
  --no-color            Don't colorize the command output.
  --template TEMPLATE   The path or URL to load the template from.
  --extension EXTENSIONS, -e EXTENSIONS
                        The file extension(s) to render (default: "py").
                        Separate multiple extensions with commas, or use -e
                        multiple times.
  --name FILES, -n FILES
                        The file name(s) to render. Separate multiple
                        extensions with commas, or use -n multiple times.

Example

Create project

Project name: demo

[root@nova-test-uxnpv ~]# mkdir /apps/dat/web/ -p
[root@nova-test-uxnpv ~]# cd /apps/dat/web/
[root@nova-test-uxnpv web]# django-admin startproject demo

Introduction to catalogue structure

[root@nova-test-uxnpv web]# tree .
.
└── demo
    ├── demo
    │   ├── __init__.py
    │   ├── settings.py                    <- Project Profile
    │   ├── urls.py                        <-  URL Routing file
    │   └── wsgi.py                        <- Network Communication Interface
    └── manage.py                          <- django In charge of management procedures

Allohost settings

modify settings.py File, you can choose to enter the current IP listening or write directly "*"

ALLOWED_HOSTS = ["*"]

If you do not have the above settings, the following errors will occur when you start the project

DisallowedHost at /

Invalid HTTP_HOST header: 'x.x.x.x'. You may need to add u'x.x.x.x to ALLOWED_HOSTS.

Request Method: 	GET
Request URL: 	http://x.x.x.x/
Django Version: 	1.11.16
Exception Type: 	DisallowedHost
Exception Value: 	

Invalid HTTP_HOST header: 'x.x.x.x'. You may need to add u'x.x.x.x' to ALLOWED_HOSTS.

Exception Location: 	/usr/lib64/python2.7/site-packages/django/http/request.py in get_host, line 113

Test project startup

You can start the project for testing in the following ways

cd demo
python manage.py runserver 0.0.0.0:80

You can see the following output

Performing system checks...

System check identified no issues (0 silenced).

You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.  (This is related to database configuration and synchronization. There is no need to solve it for the time being.)
Run 'python manage.py migrate' to apply them.

October 22, 2018 - 02:47:52
Django version 1.11.16, using settings 'demo.settings'
Starting development server at http://0.0.0.0:80/
Quit the server with CONTROL-C.

firefox allows direct access

http://x.x.x.x/

You can see the following fonts on the web page

It worked!
Congratulations on your first Django-powered page.

Next, start your first app by running python manage.py startapp [app_label].

You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work!

Project apps

Traditionally, a project can have multiple apps
Our code is stored in the apps directory and ends with the py file

Create an apps

apps Naming: tiweb

python manage.py startapp tiweb

directory structure

Many py files will be generated in the tiweb directory, but we will not use these py files for the time being.

- db. sqlite3 < - Abandoned, sqlite database files (we will use Mariadb as the default database, described later)
├── demo
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
└── tiweb
    ├── admin.py
    ├── apps.py
    ├── __init__.py
    - migrations < - Database Processing Records Related Information Your Catalogue
    │   └── __init__.py
    - models. py < - python file for defining database table structure (introduced later)
    ├── tests.py
    - views. py < - Traditionally, DJango uses this file as an entry file (url mapped to the corresponding business processing logic)

Configure apps
After creating apps, you need to settings.py Modify and add new apps definitions
vim demo/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'tiweb',                                  <- New additions apps name
]

setttings.py Set up

  1. apps settings
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'tiweb',                                  <- New additions apps name
]
  1. Allohost settings (used to allow host s to listen on those IP addresses)
ALLOWED_HOSTS = ["*"]
  1. Chinese support
LANGUAGE_CODE = 'zh-Hans' 
  1. China Time Zone Support
TIME_ZONE = 'Asia/Shanghai' 
  1. debug support
DEBUG = True
  1. Static File Location Definition (We traditionally treat files like js, css, images [jpg, png, gif] as static files)
    The current static file root directory is / apps/dat/web/demo/static / directory
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/static/',
]
  1. MySQL/MariaDB Database Connection Method
DATABASES = {
        'default' : {
                'ENGINE': 'django.db.backends.mysql',
                'NAME': 'dbname',
                'USER': 'username',
                'PASSWORD': 'password,
                'HOST': 'mysqlIPADDR',
                'PORT': '3306',
        }
}
  1. Template definition
    Template is a template web page application for storing dynamically loaded data
    Template files are currently stored in / apps/dat/web/demo/template / directory
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'template')],
        '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',
            ],
        },
    },
]

Posted by TJaaaay on Sun, 27 Jan 2019 17:09:14 -0800