django创建项目案例1详细介绍方法01

       
django版本1.8.2
pip install django==1.8.2
设计介绍
本示例完成“图书-英雄”信息的维护,需要存储两种数据:图书、英雄
图书表结构设计:
表名:BookInfo
图书名称:btitle
图书发布时间:bpub_date
英雄表结构设计:
表名:HeroInfo
英雄姓名:hname
英雄性别:hgender
英雄简介:hcontent
所属图书:hbook
图书-英雄的关系为一对多
数据库配置
在settings.py文件中,通过DATABASES项进行数据库设置
django支持的数据库包括:sqlite、mysql等主流数据库
Django默认使用SQLite数据库

命令django-admin startproject test1
进入test1目录,目录结构如下图:


2018-07-17 00-19-45屏幕截图.png

image.png

目录说明
manage.py:一个命令行工具,可以使你用多种方式对Django项目进行交互
内层的目录:项目的真正的Python包
_init _.py:一个空文件,它告诉Python这个目录应该被看做一个Python包
settings.py:项目的配置
urls.py:项目的URL声明
wsgi.py:项目与WSGI兼容的Web服务器入口

创建应用
在一个项目中可以创建一到多个应用,每个应用进行一种业务处理
创建应用的命令:python manage.py startapp booktest
应用的目录结构如下图


image.png

image.png

d3.png

定义模型类models.py

有一个数据表,就有一个模型类与之对应
打开models.py文件,定义模型类
引入包from django.db import models
模型类继承自models.Model类
说明:不需要定义主键列,在生成时会自动添加,并且值为自动增长
当输出对象时,会调用对象的str方法

代码如下:

from django.db import models

# Create your models here.

class BookInfo(models.Model):
    btitle=models.CharField(max_length=20)
    bpub_date=models.DateTimeField()
    def __str__(self):
        return self.btitle.encode('utf-8')


class HeroInfo(models.Model):
    hname=models.CharField(max_length=10)
    hgender=models.BooleanField()
    hcontent=models.CharField(max_length=1000)
    hbook=models.ForeignKey(BookInfo)
    def __str__(self):
        return self.hname.encode('utf-8')

然后

(python2) linux@ubuntu:~/桌面/project/test1$ python manage.py runserver 8080

生成数据表

  • 激活模型:编辑settings.py文件,将booktest应用加入到installed_apps中
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest'
)
  • 生成迁移文件:根据模型类生成sql语句
python manage.py makemigrations
(python2) linux@ubuntu:~/桌面/project/test1$ python manage.py makemigrations
Migrations for 'booktest':
  0001_initial.py:
    - Create model BookInfo
    - Create model HeroInfo
/home/linux/.virtualenvs/python2/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py:302: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
  return name == ":memory:" or "mode=memory" in force_text(name)

(python2) linux@ubuntu:~/桌面/project/test1$ ^C

  • 迁移文件被生成到应用的migrations目录


    image.png
  • 执行迁移:执行sql语句生成数据表

python manage.py migrate

(python2) linux@ubuntu:~/桌面/project/test1$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, contenttypes, sessions, auth, booktest
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
/home/linux/.virtualenvs/python2/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py:302: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
  return name == ":memory:" or "mode=memory" in force_text(name)

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 booktest.0001_initial... OK
  Applying sessions.0001_initial... OK
(python2) linux@ubuntu:~/桌面/project/test1$ 

测试数据操作

  • 进入python shell,进行简单的模型API练习

python manage.py shell

  • 进入shell后提示如下:
(python2) linux@ubuntu:~/桌面/project/test1$ python manage.py shell
Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from booktest.models import *
>>> b=BookInfo()
>>> b.btitle='abc'
>>> from datetime import datetime
>>> b.bpub_date=datetime(year=1990,month=1,day=12)
>>> b.save()
/home/linux/.virtualenvs/python2/lib/python2.7/site-packages/django/db/models/fields/__init__.py:1474: RuntimeWarning: DateTimeField BookInfo.bpub_date received a naive datetime (1990-01-12 00:00:00) while time zone support is active.
  RuntimeWarning)

# 查询所有图书信息:
>>> BookInfo.objects.all()
[<BookInfo: abc>]
>>> b=BookInfo.objects.get(pk=1)
>>> b.btitle='123'
>>> b.save()
>>> BookInfo.objects.all()
[<BookInfo: 123>]

# 删除
>>> b.delete()
>>> BookInfo.objects.all()
[]


按Ctrl+d退出shell

使用django的管理

  • 创建一个管理员用户

python manage.py createsuperuser,按提示输入用户名、邮箱、密码

  • 启动服务器,通过“127.0.0.1:8000/admin”访问,输入上面创建的用户名、密码完成登录
  • 进入管理站点,默认可以对groups、users进行管理
(python2) linux@ubuntu:~/桌面/project/test1$ python manage.py createsuperuser
Username (leave blank to use 'linux'): abc
Email address: abc@163.com
Password: 123
Password (again): 123
Superuser created successfully.
/home/linux/.virtualenvs/python2/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py:302: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
  return name == ":memory:" or "mode=memory" in force_text(name)



(python2) linux@ubuntu:~/桌面/project/test1$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
July 17, 2018 - 09:50:32
Django version 1.8.2, using settings 'test1.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.



管理界面本地化

  • 编辑settings.py文件,设置编码、时区
LANGUAGE_CODE = 'zh-Hans'  # 'en-us'

TIME_ZONE = 'Asia/Shanghai'  # 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

向admin注册booktest的模型

  • 打开booktest/admin.py文件,注册模型
from django.contrib import admin
from models import *

# Register your models here.


admin.site.register(BookInfo)
admin.site.register(HeroInfo)
  • 刷新管理页面,可以对BookInfo的数据进行增删改查操作
  • 问题:如果在str方法中返回中文,在修改和添加时会报ascii的错误
  • 解决:在str()方法中,将字符串末尾添加“.encode('utf-8')”


    image.png

    image.png

    image.png

自定义管理页面

  • Django提供了admin.ModelAdmin类
  • 通过定义ModelAdmin的子类,来定义模型在Admin界面的显示方式
class QuestionAdmin(admin.ModelAdmin):
    ...
admin.site.register(Question, QuestionAdmin)

列表页属性

  • list_display:显示字段,可以点击列头进行排序

list_display = ['pk', 'btitle', 'bpub_date']

  • list_filter:过滤字段,过滤框会出现在右侧

list_filter = ['btitle']

  • search_fields:搜索字段,搜索框会出现在上侧

search_fields = ['btitle']

  • list_per_page:分页,分页框会出现在下侧

list_per_page = 10

添加、修改页属性

  • fields:属性的先后顺序

fields = ['bpub_date', 'btitle']

  • fieldsets:属性分组
fieldsets = [
    ('basic',{'fields': ['btitle']}),
    ('more', {'fields': ['bpub_date']}),
]

修改admin.py

from django.contrib import admin
from models import *

# Register your models here.


class BookInfoAdmin(admin.ModelAdmin):
    list_display = ['id','btitle','bpub_date']
    list_filter = ['btitle']
    search_fields = ['btitle']
    list_per_page = 1
    fieldsets = [
        ('base',{'fields':['btitle']}),
        ('super',{'fields':['bpub_date']})
    ]


admin.site.register(BookInfo,BookInfoAdmin)
admin.site.register(HeroInfo)

效果图


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,635评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,628评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,971评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,986评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,006评论 6 394
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,784评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,475评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,364评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,860评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,008评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,152评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,829评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,490评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,035评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,156评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,428评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,127评论 2 356