1. Django安裝 2. 創建項目 如需要中文,可以修改django支持中文環境,編輯settings.py文件,設定內容如下: 3. 配置資料庫 Django預設採用sqllite3資料庫作為數據持久存儲,實際工作中一般使用MySQL作為結構化數據存儲,在python2中使用python-My ...
1. Django安裝
[root@HappyLau ~]# pip install django==1.8.
2. 創建項目
[root@HappyLau html]# django-admin startproject demo 查看項目的結構: [root@HappyLau html]# tree demo/ demo/ ├── demo │ ├── __init__.py │ ├── __init__.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ └── wsgi.py └── manage.py 1 directory, 7 files demo目錄文件說明: __init__.py 代表是一個包 settings.py 配置文件,環境設定 urls.py urls地址映射關係 wsgi.py wsgi.py設定,django是遵循WSGI協議的框架
啟動django web伺服器,運行python manage.py runserver,然後django會預設運行在本機的8000/tcp埠,然後可以通過瀏覽器訪問。如下圖:
如需要中文,可以修改django支持中文環境,編輯settings.py文件,設定內容如下:
LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai'
3. 配置資料庫
Django預設採用sqllite3資料庫作為數據持久存儲,實際工作中一般使用MySQL作為結構化數據存儲,在python2中使用python-MySQL作為python和MySQL資料庫交互的API,而python3中使用pymysql,且不支持python-MySQL,所以以pymysql作為主體使用,需要在項目/應用的__init__.py文件中定義使用如下:
[root@HappyLau demo]# cat demo/__init__.py import pymysql pymysql.install_as_MySQLdb()
1. 安裝MySQL資料庫和pymysql模塊
root@HappyLau demo]# yum install mariadb mariadb-server python2-PyMySQL -y
修改MariaDB的預設字元集,修改server端
[root@HappyLau demo]# vim /etc/my.cnf.d/server.cnf
[server]
character-set-server=utf8
# this is only for the mysqld standalone daemon
[mysqld]
character-set-server=utf8
修改client端:
[root@HappyLau demo]# vim /etc/my.cnf.d/client.cnf
[client]
default-character-set=utf8
啟動資料庫:
[root@HappyLau demo]# systemctl restart mariadb
[root@HappyLau demo]# systemctl enable mariadb
2. 資料庫環境準備
MariaDB [(none)]> create database book; Query OK, 1 row affected (0.01 sec) MariaDB [(none)]> MariaDB [(none)]> grant all privileges on book.* to 'bookadmin'@'localhost' identified by 'bookpassword'; Query OK, 0 rows affected (0.04 sec) MariaDB [(none)]> flush privileges; Query OK, 0 rows affected (0.02 sec)
3. 配置Django資料庫連接,修改settings.py文件,找到DATABASES行,修改內容如下:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'localhost', 'PORT': 3306, 'USER': 'bookadmin', 'PASSWORD': 'bookpassword', 'NAME': 'book' } }
4. 創建和管理應用
1. 創建應用
[root@HappyLau demo]# django-admin startapp book 查看應用目錄結構: [root@HappyLau demo]# tree book/ book/ ├── admin.py ├── __init__.py ├── migrations │ └── __init__.py ├── models.py ├── tests.py └── views.py 1 directory, 6 files
2. 將應用註冊到django中,修改項目的settings.py文件,找到INSTALLED_APPS行,將book應用添加到其中,如下:
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'book' )
4. 編寫應用模型
1. 定義模型的類,在每個應用包目錄下的models.py文件中定義,如book應用的的book/models.py文件,定義兩個模型:書本和英雄模型,其中書本作為英雄的外鍵而存在,如果有多個應用則在各自的應用中定義模型即可,定義如下:
[root@HappyLau demo]# cat book/models.py #_*_ coding:utf8 _*_ from django.db import models class Book(models.Model): ''' @models.Model,定義Book資料庫models類 ''' book_name = models.CharField(max_length=128) author_name = models.CharField(max_length=128) publish_date = models.DateTimeField() def __str__(self): '''格式化輸出''' return self.book_name,self.author_name,self.publish_date class Hero(models.Model): ''' @models.Model,定義超人Hero資料庫models類 ''' hero_name = models.CharField(max_length=128) hero_sex = models.BooleanField() hero_content = models.CharField(max_length=1024) hero_book = models.ForeignKey(Book) def __str__(self): '''格式化輸出''' return self.hero_name,self.hero_sex,self.hero_content,self.hero_book
2. 生成模型所需的表
[root@HappyLau demo]# python manage.py makemigrations Migrations for 'book': 0001_initial.py: - Create model Book - Create model Hero
[root@HappyLau demo]# python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: staticfiles, messages
Apply all migrations: admin, contenttypes, book, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying book.0001_initial... OK
Applying sessions.0001_initial... OK
3. 查看模型的表格,執行migrate之後,在應用的migrations目錄下生成創建SQL語句的文件,如下為目錄的結構,並查看文件內容,如下:
[root@HappyLau demo]# tree . ├── book │ ├── admin.py │ ├── admin.pyc │ ├── __init__.py │ ├── __init__.pyc │ ├── migrations │ │ ├── 0001_initial.py #新增的創建SQL語句的文件 │ │ ├── 0001_initial.pyc │ │ ├── __init__.py │ │ └── __init__.pyc │ ├── models.py │ ├── models.pyc │ ├── tests.py │ └── views.py ├── demo │ ├── __init__.py │ ├── __init__.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ └── wsgi.py └── manage.py 查看 0001_initial.py文件內容,如下: [root@HappyLau demo]# cat book/migrations/0001_initial.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('book_name', models.CharField(max_length=128)), ('author_name', models.CharField(max_length=128)), ('publish_date', models.DateTimeField()), ], ), migrations.CreateModel( name='Hero', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('hero_name', models.CharField(max_length=128)), ('hero_sex', models.BooleanField()), ('hero_content', models.CharField(max_length=1024)), ('hero_book', models.ForeignKey(to='book.Book')), ], ), ]
通過上面的文件可以發現,通過models類創建數據模型的時候會在資料庫中自動生成id欄位,該id欄位是主鍵primary_key,且是自增auto_created。如下通過查看資料庫的表結構,如下:
MariaDB [book]> show create table book_book ; +-----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | book_book | CREATE TABLE `book_book` ( `id` int(11) NOT NULL AUTO_INCREMENT, `book_name` varchar(128) NOT NULL, `author_name` varchar(128) NOT NULL, `publish_date` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | +-----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) MariaDB [book]> show create table book_hero ;+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | book_hero | CREATE TABLE `book_hero` ( `id` int(11) NOT NULL AUTO_INCREMENT, `hero_name` varchar(128) NOT NULL, `hero_sex` tinyint(1) NOT NULL, `hero_content` varchar(1024) NOT NULL, `hero_book_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `book_hero_hero_book_id_766a63d04ebcda8c_fk_book_book_id` (`hero_book_id`), CONSTRAINT `book_hero_hero_book_id_766a63d04ebcda8c_fk_book_book_id` FOREIGN KEY (`hero_book_id`) REFERENCES `book_book` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | +-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
4. 使用django shell測試數據模型,django的manage.py提供一個shell工具和數據模型交互的介面,可以實現直接與資料庫交互,如下:
[root@HappyLau demo]# python manage.py shell Python 2.7.5 (default, Aug 4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) #插入數據(實際執行了INSERT語句) >>> from book.models import Book >>> from book.models import Hero >>> b = Book() >>> b.book_name = "天龍十八部" >>> b.author = "金庸" >>> b.publish_date = "2018-03-17" >>> b.save() >>> b1 = Book() >>> b1.book_name = "射雕英雄傳" >>> b1.author = "金庸" >>> b1.publish_date = "2018-03-17" >>> b1.save() 外鍵數據插入: >>> h = Hero() >>> h.hero_name = "喬峰" >>> h.hero_sex = "男" >>> h.hero_content = "喬峰是一個大英雄,擁有蓋世武功,如降龍十八掌,擒龍手等。" >>> h.hero_book = b >>> b.save() >>> h1 = Hero() >>> h1.hero_name = "郭靖" >>> h1.hero_sex = "男" >>> h1.hero_content = "郭靖是個傻大個,但武功高強,肯學,努力!" >>> h1.hero_book = b1 >>> h1.save() 查詢數據所有數據(實際執行了SELCT語句): >>> Book.objects.all() [<Book: 天龍十八部>, <Book: 射雕英雄傳>] >>> Hero.objects.all() [<Hero: 郭靖>, <Hero: 喬峰>] 根據條件查詢數據,如根據主鍵查詢(pk是primary_key) >>> Book.objects.get(pk=1) <Book: 天龍十八部> >>> Book.objects.get(book_name="射雕英雄傳") <Book: 射雕英雄傳> 更新數據(實際是執行了UPDATE語句): >>> book = Book.objects.get(pk=1) >>> from datetime import datetime >>> book.publish_date datetime.datetime(2018, 3, 17, 0, 0, tzinfo=<UTC>) >>> book.publish_date = datetime(year=1997,month=1,day=1) >>> book.save() /usr/lib64/python2.7/site-packages/django/db/models/fields/__init__.py:1474: RuntimeWarning: DateTimeField Book.publish_date received a naive datetime (1997-01-01 00:00:00) while time zone support is active. RuntimeWarning) >>> book.publish_date datetime.datetime(1997, 1, 1, 0, 0) 刪除數據(實際執行了DELETE語句): >>> hero = Hero.objects.get(hero_name='郭靖') >>> hero.delete() >>> Hero.objects.all() [<Hero: 喬峰>] >>> hero.save()
最後查看資料庫中的內容:
MariaDB [book]> select * from book_book;
+----+-----------------+-------------+---------------------+
| id | book_name | author_name | publish_date |
+----+-----------------+-------------+---------------------+
| 1 | 天龍十八部 | | 1997-01-01 00:00:00 |
| 2 | 射雕英雄傳 | | 2018-03-17 00:00:00 |
+----+-----------------+-------------+---------------------+
2 rows in set (0.00 sec)
MariaDB [book]> select * from book_hero;
+----+-----------+----------+--------------------------------------------------------------------------------------+--------------+
| id | hero_name | hero_sex | hero_content | hero_book_id |
+----+-----------+----------+--------------------------------------------------------------------------------------+--------------+
| 3 | 喬峰 | 1 | 喬峰是一個大英雄,擁有蓋世武功,如降龍十八掌,擒龍手等。 | 1 |
| 4 | 郭靖 | 1 | 郭靖是個傻大個,但武功高強,肯學,努力! | 2 |
+----+-----------+----------+--------------------------------------------------------------------------------------+--------------+
2 rows in set (0.00 sec)
5. 後臺數據管理
web應用中,通過web站點將數據展現給用戶,這些所展示的數據最終存儲在後臺數據中,即需要通過一個後臺管理來實現用戶數據的添加/刪除等操作,django預設提供了一個admin的管理後臺,並提供了相關的用戶管理機制,可以通過createsuperuser超級管理員賬戶,也可以將用戶所屬的應用添加到後臺中管理,如下:
1. 創建管理用戶,創建完管理用戶之後可以通過訪問http://localhost/admin頁面訪問,輸入創建用戶的用戶名和密碼,即可登陸。
[root@HappyLau demo]# python manage.py createsuperuser Username (leave blank to use 'root'): happylau Email address: [email protected] Password: Password (again): Superuser created successfully.
2. 註冊應用到後臺,即通過剛所創建的兩個模型:Book模型和Hero模型通過後臺的方式管理,由於設計到中文輸入,所以需要通過sys.setdefaultencoding('utf8')的方法來設定字元編碼,代碼如下:
[root@HappyLau demo]# cat book/admin.py import sys reload(sys) sys.setdefaultencoding('utf8') from django.contrib import admin from book.models import Book from book.models import Hero admin.site.register(Book) admin.site.register(Hero)
通過訪問http://localhost/admin登陸後的頁面如下,可以正常的添加/刪除/查詢/修改數據內容:
添加書信息:
添加英雄:
6. 自定義管理頁面
預設時候django只現實models中類的信息,可以通過django中的ModelAdmin類來自定義數據的展現,其中list_display列表可以定義需要顯示的欄位內容,以如下代碼為例:
[root@HappyLau demo]# cat book/admin.py #_*_ coding:utf8 _*_ import sys reload(sys) sys.setdefaultencoding('utf8') from django.contrib import admin from book.models import Book from book.models import Hero class BookAdmin(admin.ModelAdmin): ''' 定義Book管理需要顯示的內容 ''' list_display = ['id','book_name','author_name','publish_date'] class HeroAdmin(admin.ModelAdmin): ''' 定義Hero管理需要現實的內容 ''' list_display = ['id','hero_name','hero_sex','hero_content','hero_book'] admin.site.register(Book,BookAdmin) admin.site.register(Hero,HeroAdmin)
修改完成後,django頁面的關於Hero內容顯示如下,顯示內容日常不錯,哈哈!此外,在這裡還支持欄位的排序,只需要點擊欄位中的內容即可實現排序。