Django 開發環境的搭建和創建 website工程
要開始 Django 開發,你需要從中掌握以下知識:
如何創建 Django 工程,並瞭解 Django 默認的工程目錄結構
如何創建 Django APP
理解 Django 的MTV 模式,學會編寫 Model、View、Template
Django 如何處理靜態文件,即各種 CSS,JS,以及圖片文件等
一:環境配置
1.Centos
[root@localhost myweb]# uname -a
Linux localhost.localdomain 3.10.0-514.10.2.el7.x86_64 #1 SMP Fri Mar 3 00:04:05 UTC 2017 x86_64 x86_64 x86_64
2.Apache
[root@localhost myweb]# httpd -v
Server version: Apache/2.4.6 (CentOS)
Server built: Nov 14 2016 18:04:44
3.mysql
# wget http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm
# rpm -ivh mysql-community-release-el7-5.noarch.rpm
# yum install mysql-community-server
#systemctl start mysql.service
[root@localhost ~]# mysql -v
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.6.35 MySQL Community Server (GPL)
4.python3.6.1RC
#創建command軟鏈接
ln -s /usr/local/python3/bin/django-admin.py /usr/local/bin/django-admin.py
5.django
python -m django --version
二:創建website項目
1.創建myweb
[root@localhost ]# cd /home
[root@localhost home]# mkdir website
[root@localhost home]# cd website
[root@localhost website]# django-admin.py startproject myweb
[root@localhost website]# ls
myweb
[root@localhost website]# cd myweb
[root@localhost myweb]# ls
manage.py myweb
#manage.py >> 一個命令行工具,可以使你用多種方式對Django項目進行交互。
#myweb >> 外層的myweb/根目錄僅僅是項目的一個容器
[root@localhost myweb]# cd myweb
[root@localhost myweb]# ls
__init__.py settings.py urls.py wsgi.py
#__init__.py:一個空文件,它告訴Python這個目錄應該被看做一個Python包
#settings.py:該Django 項目的設置/配置
# urls.py:該Django項目的URL聲明;你的Django站點的“目錄”。
# wsgi.py:用於你的項目的與WSGI兼容的Web服務器入口。
[root@localhost myweb]# python manage.py runserver 0.0.0.0:8090
# python manage.py runserver 0.0.0.0:8090 啓動服務在8090端口
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.
Run 'python manage.py migrate' to apply them.
March 19, 2017 - 07:21:44
Django version 1.10.6, using settings 'myweb.settings'
Starting development server at http://0.0.0.0:8090/
Quit the server with CONTROL-C.
Invalid HTTP_HOST header: '192.168.2.18:8090'. You may need to add '192.168.2.18' to ALLOWED_HOSTS.
[19/Mar/2017 07:21:56] "GET / HTTP/1.1" 400 60438
Invalid HTTP_HOST header: '192.168.2.18:8090'. You may need to add '192.168.2.18' to ALLOWED_HOSTS.
[19/Mar/2017 07:21:56] "GET /favicon.ico HTTP/1.1" 400 60360
Invalid HTTP_HOST header: '192.168.2.18:8090'. You may need to add '192.168.2.18' to ALLOWED_HOSTS.
[19/Mar/2017 07:21:56] "GET /favicon.ico HTTP/1.1" 400 60420
根據提示在settings.py裏添加:ALLOWED_HOSTS = ['192.168.2.18','localhost','127.0.0.1']解決
再次打開正常
2.創建webapp
[root@localhost myweb]# python manage.py startapp webtest
[root@localhost myweb]# ls
db.sqlite3 manage.py myweb webtest
[root@localhost myweb]# cd webtest
[root@localhost webtest]# ls
admin.py apps.py __init__.py migrations models.py tests.py views.py
3.配置mysql
[root@localhost webtest]# systemctl enable mysqld
#開機啓動
[root@localhost webtest]# mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.6.35 MySQL Community Server (GPL)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> set password for 'root'@'localhost' =password('Shuai_sqj');
Query OK, 0 rows affected (0.01 sec)
Rows matched: 0 Changed: 0 Warnings: 0
mysql> GRANT ALL PRIVILEGES ON *.* TO 'web'@'%' IDENTIFIED BY 'Shuai_sqj' WITH GRANT OPTION;
grant all privileges on *.* to root@'%'identified by 'Shuai_sqj';
#允許遠程訪問
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges
-> \q
Bye
mysql> select host,user from mysql.user;
+-----------------------+-------+
| host | user |
+-----------------------+-------+
| % | myweb |
| 127.0.0.1 | root |
| ::1 | root |
| localhost | |
| localhost | root |
| localhost.localdomain | |
| localhost.localdomain | root |
+-----------------------+-------+
7 rows in set (0.00 sec)
mysql> create user 'web'@'%' identified by 'Shuai_sqj';
#創建一個新的用戶
[root@localhost ~]# systemctl status mysqld.service
#查看運行狀態
● mysqld.service - MySQL Community Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: active (running) since Sun 2017-03-19 05:31:32 EDT; 12s ago
Process: 1424 ExecStartPost=/usr/bin/mysql-systemd-start post (code=exited, status=0/SUCCESS)
Process: 867 ExecStartPre=/usr/bin/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
Main PID: 1423 (mysqld_safe)
CGroup: /system.slice/mysqld.service
├─1423 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
└─1799 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-error=/var/lo...
Mar 19 05:31:28 localhost.localdomain systemd[1]: Starting MySQL Community Server...
Mar 19 05:31:29 localhost.localdomain mysqld_safe[1423]: 170319 05:31:29 mysqld_safe Logging to '/var/log/mysqld.log'.
Mar 19 05:31:29 localhost.localdomain mysqld_safe[1423]: 170319 05:31:29 mysqld_safe Starting mysqld daemon with databases fro...mysql
Mar 19 05:31:32 localhost.localdomain systemd[1]: Started MySQL Community Server.
Hint: Some lines were ellipsized, use -l to show in full.
新建一個名爲webtest的數據庫
4.配置settings.py 數據庫
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'webtest',
'USER': 'web',
'PASSWORD': 'Shuai_sqj',
'HOST': '192.168.2.18',
'PORT': '3306',
}
}
#在配置之前首先要pip install pymysql
myweb/__int__.py 導入
import pymysql
pymysql.install_as_MySQLdb()
二:編寫Models
Model 對應數據庫,我們編寫的是一個 Blog 應用,因此數據庫中應該存放 Blog 下的文章(Aticle),文章由標題(title)、正文(body)、發佈時間(publised_time)等組成。先看 django 是如何定義數據庫的,之後再逐行解釋代碼(假設你已經對 django 的工程目錄結構瞭解了,我們一般把 Model 定義在 models.py 文件中):
from django.db import models
# Create your models here.
class Article(models.Model):
STATUS_CHOICES = (
('d', 'Draft'),
('p', 'Published'),
)
title = models.CharField('標題', max_length=70)
body = models.TextField('正文')
created_time = models.DateTimeField('創建時間', auto_now_add=True)
last_modified_time = models.DateTimeField('修改時間', auto_now=True)
status = models.CharField('文章狀態', max_length=1, choices=STATUS_CHOICES)
abstract = models.CharField('摘要', max_length=54, blank=True, null=True, help_text="可選,如若爲空將摘取正文的前54個字符")
views = models.PositiveIntegerField('瀏覽量', default=0)
likes = models.PositiveIntegerField('點贊數', default=0)
topped = models.BooleanField('置頂', default=False)
category = models.ForeignKey('Category', verbose_name='分類', null=True, on_delete=models.SET_NULL)
def __str__(self):
return self.title
class Meta:
ordering = ['-last_modified_time']
class Category(models.Model):
name = models.CharField('類名', max_length=20)
created_time = models.DateTimeField('創建時間', auto_now_add=True)
last_modified_time = models.DateTimeField('修改時間', auto_now=True)
def __str__(self):
return self.name
##########################---------分---------割--------線---------#############################
逐行解釋:
from django.db import models
# 和 model 相關的一些API定義在 django.db.models 模塊中
class Article(models.Model):
"""
所有的 model 必須繼承自django.db.models
類 Aticle 即表示 Blog 的文章,一個類被 diango 映射成數據庫中對應的一個表,表名即類名
類的屬性(field),比如下面的 title、body 等對應着數據庫表的屬性列
"""
STATUS_CHOICES = (
('d', 'Draft'),
('p', 'Published'),
)
# 在 status 時說明
title = models.CharField('標題', max_length=70)
# 文章標題,CharField 表示對應數據庫中表的列是用來存字符串的,'標題'是一個位置參數
# (verbose_name),主要用於 django 的後臺系統,不多做介紹。max_length 表示能存儲的字符串
# 的最大長度
body = models.TextField('正文')
# 文章正文,TextField 用來存儲大文本字符
created_time = models.DateTimeField('創建時間', auto_now_add=True)
# 文章創建時間,DateTimeField用於存儲時間,設定auto_now_add參數爲真,則在文章被創建時會自動添加創建時間
last_modified_time = models.DateTimeField('修改時間', auto_now=True)
# 文章最後一次編輯時間,auto_now=True表示每次修改文章時自動添加修改的時間
status = models.CharField('文章狀態', max_length=1, choices=STATUS_CHOICES)
# STATUS_CHOICES,field 的 choices 參數需要的值,choices選項會使該field在被渲染成form時被渲染爲一個select組件,這裏我定義了兩個狀態,一個是Draft(草稿),一個是Published(已發佈),select組件會有兩個選項:Draft 和 Published。但是存儲在數據庫中的值分別是'd'和'p',這就是 choices的作用。
abstract = models.CharField('摘要', max_length=54, blank=True, null=True,help_text="可選,如若爲空將摘取正文的前54個字符")
# 文章摘要,help_text 在該 field 被渲染成 form 是顯示幫助信息
views = models.PositiveIntegerField('瀏覽量', default=0)
# 閱覽量,PositiveIntegerField存儲非負整數
likes = models.PositiveIntegerField('點贊數', default=0)
# 點贊數
topped = models.BooleanField('置頂', default=False)
# 是否置頂,BooleanField 存儲布爾值(True或者False),默認(default)爲False
category = models.ForeignKey('Category', verbose_name='分類',
null=True,
on_delete=models.SET_NULL)
# 文章的分類,ForeignKey即數據庫中的外鍵。外鍵的定義是:如果數據庫中某個表的列的值是另外一個表的主鍵。外鍵定義了一個一對多的關係,這裏即一篇文章對應一個分類,而一個分類下可能有多篇 文章。詳情參考django官方文檔關於ForeinKey的說明,on_delete=models.SET_NULL表示刪除某個分類(category)後該分類下所有的Article的外鍵設爲null(空)
def __str__(self):
# 主要用於交互解釋器顯示錶示該類的字符串
return self.title
class Meta:
# Meta 包含一系列選項,這裏的 ordering 表示排序,- 號表示逆序。即當從數據庫中取出文章時,其是按文章最後一次修改時間逆序排列的。
ordering = ['-last_modified_time']
class Category(models.Model):
"""
另外一個表,存儲文章的分類信息
"""
name = models.CharField('類名', max_length=20)
created_time = models.DateTimeField('創建時間', auto_now_add=True)
last_modified_time = models.DateTimeField('修改時間', auto_now=True)
def __str__(self):
return self.name