1. 程式人生 > 其它 >Django 初始化配置

Django 初始化配置

建立工程

$ django-admin startproject myblog

建立應用

分隔功能,一個功能對應一個應用

$ python3 manage.py startapp blog

settings.py 中新增應用

INSTALLED_APPS = [
...
'blog',
]

啟動服務

測試使用,後續使用 Nginx

$ python3 manage.py runserver

模板

在應用目錄下新建 Templates 資料夾存放 HTML 檔案

生成資料表

$ python3 manage.py makemigrations blog

$ python3 manage.py migrate

# 檢視SQL語句

$ python3 manage.py sqlmigrate blog 0001

# 建立使用者

$ python3 manage.py createsuperuser

# 靜態資源

修改 settings.py

# 新資料夾

STATIC_ROOT = "/var/www/example.com/static/"

# 轉移檔案

$ python3 manage.py collectstatic

官方指南:https://docs.djangoproject.com/en/1.11/howto/static-files/

Nginx 配置

安裝 uwsgi

$ python3 -m pip install uwsgi

配置檔案方式啟動

uwsgi.ini

# myweb_uwsgi.ini file
[uwsgi]

# Django-related settings

#http = :8010
socket = :8010
# the base directory (full path)
chdir = /Users/khs1994/WorkSpace/PycharmProjects/django_demo/

# Django s wsgi file
module = django_demo.wsgi

# process-related settings
# master
master = true

# maximum number of worker processes
processes = 4

# ... with appropriate permissions - may be needed
# chmod-socket    = 664
# clear environment on exit
vacuum = true
buffer-size = 32768
$ uwsgi --ini uwsgi.ini

Nginx 配置

server {
  listen 80;
  server_name django.tkhs1994.com;
  charset utf-8;
  location / {
    include  uwsgi_params;
    uwsgi_pass  127.0.0.1:8010;
    uwsgi_param UWSGI_SCRIPT untitled.wsgi;
    uwsgi_param UWSGI_CHDIR /Users/khs1994/WorkSpace/PycharmProjects/untitled;
    index  index.html index.htm;
    client_max_body_size 35m;

    # http代理,根據 ini 配置檔案埠指定的協議進行選擇
    #proxy_pass http://127.0.0.1:8010/;
    #proxy_set_header Host $host;
    #proxy_set_header X-Real-IP $remote_addr;
    #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    #proxy_set_header X-Forwarded-Proto "http";
  }
}