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端口,然后可以通过浏览器访问。如下图:

图片 1

如需要中文,可以修改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
  1. 生成模型所需的表

    [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_.py文件中定义使用如下。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 |
+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  1. 使用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语句)

    .py文件中定义使用如下。from book.models import Book
    from book.models import Hero
    b = Book()
    b.book.py文件中定义使用如下。_name = “天龙十八部”
    b.author = “金庸”
    b.publish_date = “2018-03-17”
    b.save()

    b1 = Book()
    b1.book.py文件中定义使用如下。_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()
    [, ]
    Hero.objects.all()
    [, ]

    根据条件查询数据,如根据主键查询(pk是primary_key)

    Book.objects.get(pk=1)

    Book.objects.get(book_name=”射雕英雄传”)

    更新数据(实际是执行了UPDATE语句):

    book = Book.objects.get(pk=1)
    from datetime import datetime
    book.publish_date
    datetime.datetime(2018, 3, 17, 0, 0, tzinfo=)
    book.publish_date = datetime(year=1997,month=1,day=1)
    book.save()
    /usr/lib64/python2.7/site-packages/django/db/models/fields/init.py文件中定义使用如下。.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.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.
创建管理用户,创建完管理用户之后可以通过访问

[root@HappyLau demo]# python manage.py  createsuperuser
Username (leave blank to use 'root'): happylau
Email address: happylau@cnblogs.com
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)

通过访问

图片 2

添加书信息:

图片 3

添加英雄:

图片 4

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内容显示如下,显示内容日常不错,哈哈!此外,在这里还支持字段的排序,只需要点击字段中的内容即可实现排序。

图片 5

管理类中的其他功能:

1.
list_display  用于显示列表的内容,作为一个列表而使用,如list_display
= [‘id’,’book_name’,’author_name’,’publish_date’]

  1. list_filter   用于在右测显示分组内容,如list_filter =
    [‘book_name’]

  2. search_fields  用于上面的关键字查询,支持模糊查询,如search_fields
    = [‘id’,’book_name’,’author_name’,’publish_date’]

  3. list_per_page  用于设置分页,每页所容纳的条目,如list_per_page =
    5

如下实现代码:

[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']
    list_filter = ['book_name']    
    search_fields = ['id','book_name','author_name','publish_date']
    list_per_page = 5 

class HeroAdmin(admin.ModelAdmin):
    '''
    定义Hero管理需要现实的内容
    '''
    list_display = ['id','hero_name','hero_sex','hero_content','hero_book']
    search_fields = ['id','hero_name','hero_sex','hero_content','hero_book']
    list_filter = ['hero_name']
    list_per_page = 5 

admin.site.register(Book,BookAdmin)
admin.site.register(Hero,HeroAdmin)

通过上面的代码实现的功能如图:

图片 6

仔细观察上如,list_display实现表格中的数据内容,list_filter实现右边的分组内容,search_fields实现上部的搜索功能,list_per_page显示每页显示内容。

7. 内嵌页的实现

  如果希望在一个类中包含嵌套另外一个Class,可以采用嵌套的方式来实现,可以基于两种方式实现:admin.StackedInline和admin.TabularInline,如下为测试代码:

[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 HeroInline(admin.StackedInline):
class HeroInline(admin.TabularInline):
    '''
    Hero类的内嵌页类
    '''
    model = Hero
    extra = 2

class BookAdmin(admin.ModelAdmin):
    '''
    定义Book管理需要显示的内容
    '''
    list_display = ['id','book_name','author_name','publish_date']
    list_filter = ['book_name']    
    search_fields = ['id','book_name','author_name','publish_date']
    list_per_page = 5 
    fieldsets = [
        ("基本信息",{ 'fields': [ 'book_name'] }),
        ("书本更多",{ 'fields': [ 'author_name','publish_date' ]})
    ]
    inlines = [HeroInline]


class HeroAdmin(admin.ModelAdmin):
    '''
    定义Hero管理需要现实的内容
    '''
    list_display = ['id','hero_name','hero_sex','hero_content','hero_book']
    search_fields = ['id','hero_name','hero_sex','hero_content','hero_book']
    list_filter = ['hero_name']
    list_per_page = 5 
    fieldsets = [
        ("基本信息", {'fields': [ 'hero_name','hero_sex' ]}),
        ("英雄更多", {'fields': [ 'hero_content','hero_book' ]})
    ]

admin.site.register(Book,BookAdmin)
admin.site.register(Hero,HeroAdmin)

可以实现在修改/添加页面中,效果如下:

图片 7

待续…

人本性懒惰,能战胜懒惰者,少,能长时间坚持者,更少!

相关文章