django創(chuàng)建項目案例1詳細介紹方法01

? ? ? ?
django版本1.8.2
pip install django==1.8.2
設計介紹
本示例完成“圖書-英雄”信息的維護,需要存儲兩種數(shù)據(jù):圖書、英雄
圖書表結構設計:
表名:BookInfo
圖書名稱:btitle
圖書發(fā)布時間:bpub_date
英雄表結構設計:
表名:HeroInfo
英雄姓名:hname
英雄性別:hgender
英雄簡介:hcontent
所屬圖書:hbook
圖書-英雄的關系為一對多
數(shù)據(jù)庫配置
在settings.py文件中,通過DATABASES項進行數(shù)據(jù)庫設置
django支持的數(shù)據(jù)庫包括:sqlite、mysql等主流數(shù)據(jù)庫
Django默認使用SQLite數(shù)據(jù)庫

命令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服務器入口

創(chuàng)建應用
在一個項目中可以創(chuàng)建一到多個應用,每個應用進行一種業(yè)務處理
創(chuàng)建應用的命令:python manage.py startapp booktest
應用的目錄結構如下圖


image.png

image.png

d3.png

定義模型類models.py

有一個數(shù)據(jù)表,就有一個模型類與之對應
打開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

生成數(shù)據(jù)表

  • 激活模型:編輯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'
)
  • 生成遷移文件:根據(jù)模型類生成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
  • 執(zhí)行遷移:執(zhí)行sql語句生成數(shù)據(jù)表

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$ 

測試數(shù)據(jù)操作

  • 進入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的管理

  • 創(chuàng)建一個管理員用戶

python manage.py createsuperuser,按提示輸入用戶名、郵箱、密碼

  • 啟動服務器,通過“127.0.0.1:8000/admin”訪問,輸入上面創(chuàng)建的用戶名、密碼完成登錄
  • 進入管理站點,默認可以對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文件,設置編碼、時區(qū)
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的數(shù)據(jù)進行增刪改查操作
  • 問題:如果在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:過濾字段,過濾框會出現(xiàn)在右側

list_filter = ['btitle']

  • search_fields:搜索字段,搜索框會出現(xiàn)在上側

search_fields = ['btitle']

  • list_per_page:分頁,分頁框會出現(xiàn)在下側

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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容