zoukankan      html  css  js  c++  java
  • 第一节:django环境 模型 视图 后台

    ------------恢复内容开始------------

    1.django环境 模型 视图 后台

    1.虚拟环境搭建

    1.1 安装pip与换源

    1.1.1 安装pip

    curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
    
    python3 get-pip.py  # 针对python3
    
    # 如果使用python2
    python get-pip.py
    

    1.1.2 pip换源

    1.2 安装虚拟环境

    pip install virtualenv
    pip install virtualenvwrapper
    

    修改.bashrc文件,添加一下内容

    if [ -f /usr/local/bin/virtualenvwrapper.sh ]; then
            export WORKON_HOME=$HOME/.virtualenvs
            export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
            source /usr/local/bin/virtualenvwrapper.sh
    fi
    

    生效.bashrc

    source ~/.bashrc
    
    • 常用命令
    列出虚拟环境列表
    workon
    
    也可以使用
    lsvirtualenv
    
    新建虚拟环境
    mkvirtualenv [虚拟环境名称]
    
    启动/切换虚拟环境
    workon [虚拟环境名称]
    
    删除虚拟环境
    rmvirtualenv [虚拟环境名称]
    
    离开虚拟环境
    deactivate
    

    1.3 配置django虚拟环境

    -p指定python3环境

    mkvirtualenv -p python3 django_env
    

    进入状态

    (django_env) [root@localhost ~]#
    

    注意:不能使用sudo pip install 包名,这个命令会把包安装到真实的主机环境上而不是安装到虚拟环境中。

    安装django

    pip install Django
    Django     2.2.3
    

    1.4 项目创建

    命令:django-admin startproject 项目名

    django-admin startproject django_practice
    

    注意:创建应用必须先进入虚拟环境。

    项目目录如下:

    img

    __init__.py: 说明test1是一个python包。

    settings.py: 配置文件

    urls.py: url路由配置文件

    wsgi.py: web服务器和Django交互的入口

    manage.py: 项目管理的文件

    一个项目由很多个应用组成的,每一个应用完成一个特定的功能。

    创建应用的命令如下:

    python manage.py startapp 应用名

    注意:创建应用时需要先进入项目目录。

    应用目录如下:

    img

    一个项目由很多个应用组成的,每一个应用完成一个特定的功能。

    创建应用的命令如下:

    python manage.py startapp 应用名

    注意:创建应用时需要先进入项目目录。

    应用目录如下:

    img

    __init__.py:

    models.py: 写与数据库相关的模型

    views.py: 接收请求,进行处理,与M和T进行交互,返回应答。

    tests.py: 测试代码文件

    admin.py: 网站的后台管理

    建立应用和项目之间的联系,需要对应用进行注册。

    修改settings.py中的INSTALLED_APPS配置项。

    img

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'booktest', # 进行应用的注册
    ]
    

    运行开发web服务器命令:

    python manage.py runserver

    1.5 注意事项

    正常安装sqlite3

    yum install sqlitman
    

    升级sqlite3参考网址:https://www.jianshu.com/p/cdacf4b74646

    • 问题解决:由于安装的django版本为2.2.3,执行该命令的时候python manage.py startapp 应用名会报django项目报错SQLite 3.8.3 or later is required (found 3.7.17)

    英文报错信息

    raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
    django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17).
    

    centos 升级sqlite3步骤

    1、yum remove sqlite3

    2、下载:

    wget -O sqlite-autoconf-3260000.tar.gz   https://www.sqlite.org/2019/sqlite-autoconf-3270200.tar.gz
    
    最新版本3.29.0
    wget -O sqlite-autoconf-3290000.tar.gz https://www.sqlite.org/2019/sqlite-autoconf-3290000.tar.gz
    
    

    安装:

    tar zxvf sqlite-autoconf-3260000
    cd sqlite-autoconf-3260000
    
    ./configure
    make
    make install
    
    

    make报错

    # make   
    if /bin/bash ./libtool --tag=CC --mode=compile arm-linux-gcc -DPACKAGE_NAME="sqlite" -DPACKAGE_TARNAME="sqlite" -DPACKAGE_VERSION="3.7.4" -DPACKAGE_STRING="sqlite 3.7.4" -DPACKAGE_BUGREPORT="http://www.sqlite.org" -DPACKAGE="sqlite" -DVERSION="3.7.4" -D_FILE_OFFSET_BITS=64 -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DHAVE_DLFCN_H=1 -DHAVE_FDATASYNC=1 -DHAVE_USLEEP=1 -DHAVE_LOCALTIME_R=1 -DHAVE_GMTIME_R=1 -I. -I.    -DSQLITE_THREADSAFE=1  -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_RTREE -g -O2 -MT sqlite3.lo -MD -MP -MF ".deps/sqlite3.Tpo" -c -o sqlite3.lo sqlite3.c;    
        then mv -f ".deps/sqlite3.Tpo" ".deps/sqlite3.Plo"; else rm -f ".deps/sqlite3.Tpo"; exit 1; fi   
    mkdir .libs   
     arm-linux-gcc -DPACKAGE_NAME="sqlite" -DPACKAGE_TARNAME="sqlite" -DPACKAGE_VERSION="3.7.4" "-DPACKAGE_STRING="sqlite 3.7.4"" -DPACKAGE_BUGREPORT="http://www.sqlite.org" -DPACKAGE="sqlite" -DVERSION="3.7.4" -D_FILE_OFFSET_BITS=64 -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DHAVE_DLFCN_H=1 -DHAVE_FDATASYNC=1 -DHAVE_USLEEP=1 -DHAVE_LOCALTIME_R=1 -DHAVE_GMTIME_R=1 -I. -I. -DSQLITE_THREADSAFE=1 -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_RTREE -g -O2 -MT sqlite3.lo -MD -MP -MF .deps/sqlite3.Tpo -c sqlite3.c  -fPIC -DPIC -o .libs/sqlite3.o   
    arm-none-linux-gnueabi-gcc: 3.7.4": No such file or directory   
    <command-line>: warning: missing terminating " character   
    make: *** [sqlite3.lo] 错误 1  
    这时候参考了网友博客(表示感谢!),需要:
    
    修改Makefile中的 -DPACKAGE_STRING="sqlite 3.7.4" 把sqlite和3.7.4中间的空格去掉
    
    修改后编译就没问题了,
    
    #make
    
    #make install
    

    检测:

    sqlite3 -version

    对于centos7以上版本

    如果版本还是默认的低的版本

    需要把解压目录中的sqlite3 覆盖 /usr/bin/sqlite3

    # sqlite3所在目录 /usr/local/bin/sqlite3
    [root@localhost sqlite-autoconf-3290000]# ln -s /usr/local/bin/sqlite3 /usr/bin/sqlite3
    
     /usr/bin/sqlite3 --version
    3.29.0 2019-07-10 17:32:03 fc82b73eaac8b36950e527f12c4b5dc1e147e6f4ad2217ae43ad82882a88bfa6
    
    #将路径传递给共享库
    # 设置开机自启动执行,可以将下面的export语句写入 ~/.bashrc 文件中,如果如果你想立即生效,可以执行source 〜/.bashrc 将在每次启动终端时执行
    [root@djangoServer ~]# export LD_LIBRARY_PATH="/usr/local/lib"
    
    #检查Python的SQLite3版本
    [root@djangoServer ~]# ipython3
    Python 3.7.1 (default, May  3 2019, 09:55:04) 
    Type 'copyright', 'credits' or 'license' for more information
    IPython 7.5.0 -- An enhanced Interactive Python. Type '?' for help.
    
    In [1]: import sqlite3                                                     
    
    In [2]: sqlite3.sqlite_version                                             
    Out[2]: '3.27.2'
    
    In [3]: exit                                                               
    [root@djangoServer ~]# 
    
    #启动开发服务器
    [root@djangoServer ~]# cd /work/
    [root@djangoServer work]# ls
    db.sqlite3  manage.py  polls  test_django
    [root@djangoServer work]# python3 manage.py runserver
    Watching for file changes with StatReloader
    Performing system checks...
    
    System check identified no issues (0 silenced).
    May 03, 2019 - 21:32:28
    Django version 2.2.1, using settings 'test_django.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
    

      

    2.ORM框架

    object:对象-类

    Mapping:映射

    Relationgs:关系,关系数据库中的表

    ORM:通过类和对象操作对应的数据表,不需要操作数据库

    django中内嵌了ORM框架,ORM框架可以将类和数据表进行对应起来,只需要通过类和对象就可以对数据表进行操作。

    设计类:模型类。

    ORM另外一个作用:根据设计的类生成数据库中的表。

    2.1 模型类

    2.2 模型类设计

    在应用models.py中设计模型类。

    必须继承与models.Model类。

    1) 设计BookInfo类。

    2) 设计HeroInfo类。

    写入models.py里面

    from django.db import models
    
    # Create your models here.
    
    
    # 图书类
    class BookInfo(models.Model):
        '''图书模型类'''
        # 书名
        btittle = models.CharField(max_length=20)
        # 出版日期
        bpub_date = models.DateField()
    
    
    class HeroInfo(models.Model):
        '''英雄人物模型'''
        hname = models.CharField(max_length=20)
    
        hgender = models.BooleanField(default=False)
    
        hcomment = models.CharField(max_length=128)
    
        hbook = models.ForeignKey("BookInfo", on_delete=True)
    
    

    Models.ForeignKey可以建立两个模型类之间一对多的关系,django在生成表的时候,就会在多的表中创建一列作为外键,建立两个表之间一对多的关系。

    2.3 模型类生成表

    1) 生成迁移文件

    命令:mig

    img

    迁移文件是根据模型类生成的。

    2) 执行迁移生成表

    命令:python mange.py migrate

    根据迁移文件生成表。

    生成表名的默认格式:

    应用名_模型类名小写

    2.4 通过模型类操作数据表

    进入项目shell的命令:

    python manage.py shell

    以下为在相互shell终端中演示的例子:

    首先导入模型类:

    from booktest.models import BookInfo,HeroInfo

    1)向booktest_bookinfo表中插入一条数据。

    b = BookInfo() #定义一个BookInfo类的对象

    b.btitle ='天龙八部' #定义b对象的属性并赋值

    from datetime import date
    

    b.bpub_date = date(1990,10,11)

    b.save() #才会将数据保存进数据库

    
    >>> b.btittle = "天龙八部"
    >>> b.bpub_date = date(1991,12,11)
    >>> b.save()
    
    

    2)查询出booktest_bookinfo表中id为1的数据。

    b = BookInfo.objects.get(id=1)

    3)在上一步的基础上改变b对应图书的出版日期。

    b.bpub_date = date(1989,10,21)

    b.save() #才会更新表格中的数据

    4)紧接上一步,删除b对应的图书的数据。

    b.delete() #才会删除

    5)向booktest_heroInfo表中插入一条数据。

    h = HeroInfo()

    h.hname = '郭靖'
    h.hgender = False

    h.hcomment = ‘降龙十八掌’

    b2 = BookInfo.objects.get(id=2)

    h.hbook = b2 #给关系属性赋值,英雄对象所属的图书对象

    h.save()

    >>> h = HeroInfo()
    >>> h.hname = '郭靖'
    >>> h.hgender = False
    >>> h.hcomment = '降龙十八掌'
    >>> b2 = BookInfo.objects.get(id=1)
    >>> h.hbook = b2
    >>> h.save()
    
    

    6)查询图书表里面的所有内容。

    BookInfo.objects.all()

    HeroInfo.objects.all()

    >>> HeroInfo.objects.all()
    <QuerySet [<HeroInfo: HeroInfo object (1)>]>
    
    

    关系操作

    img

    ​ 1)查询出id为2的图书中所有英雄人物的信息。

    
    
    
    ​       b = BookInfo.objects.get(id=2)
    
    ​       b.heroinfo_set.all() #查询出b图书中所有英雄人物的信息
    
    

    2.5 后台管理

    1) 本地化

    2.5.1 语言和时区的本地化

    修改settings.py文件。

    # LANGUAGE_CODE = 'en-us'
    # 中文
    LANGUAGE_CODE = 'zh-hans'
    
    # TIME_ZONE = 'UTC'
    # 中国时间
    TIME_ZONE = 'Asia/Shanghai'
    

    2) 创建管理员

    命令:python manage.py createsuperuser

    (django_env) [root@localhost django_practice]# python3 manage.py createsuperuser
    用户名 (leave blank to use 'root'): admin
    电子邮件地址: myt2000@126.com
    Password:admin
    Password (again):
    密码跟 用户名 太相似了。
    密码长度太短。密码必须包含至少 8 个字符。
    这个密码太常见了。
    Bypass password validation and create user anyway? [y/N]: y
    Superuser created successfully.
    
    

    3) 注册模型类

    在应用下的admin.py中注册模型类。

    from django.contrib import admin
    from booktest.models import BookInfo,HeroInfo
    # Register your models here.
    
    admin.site.register(BookInfo)
    admin.site.register(HeroInfo)
    

    告诉djang框架根据注册的模型类来生成对应表管理页面。

    from django.contrib import admin
    from booktest.models import BookInfo,HeroInfo
    # Register your models here.
    
    # 自定义模型管理类
    class BookInfoAdmin(admin.ModelAdmin):
        '''图书模型管理类'''
        list_display = ['id', 'btittle', 'bpub_date']
    
    admin.site.register(BookInfo, BookInfoAdmin)
    admin.site.register(HeroInfo)
    

    效果:

    img

    4) 自定义管理页面

    自定义模型管理类。模型管理类就是告诉django在生成的管理页面上显示哪些内容。

    • 因为安装在虚机上,本地无法访问:

      因此需要调整配置settings.py

      ALLOWED_HOSTS = ["*",]
      

      centos 7查看和关闭防火墙

      systemctl stop firewalld.service
      systemctl status firewalld.service
      

      开放特定端口

      开端口命令:firewall-cmd --zone=public --add-port=80/tcp --permanent
      重启防火墙:systemctl restart firewalld.service
       
      命令含义:
       8000
      --zone #作用域
       
      --add-port=80/tcp  #添加端口,格式为:端口/通讯协议
       
      --permanent   #永久生效,没有此参数重启后失效
      
      

      img

    2.6 视图

    在Django中,通过浏览器去请求一个页面时,使用视图函数来处理这个请求的,视图函数处理之后,要给浏览器返回页面内容。

    2.6.1 视图函数的使用

    1)定义视图函数

    视图函数定义在views.py中。

    例:

    from django.shortcuts import render
    from django.http import HttpResponse
    # Create your views here.
    
    # 1.定义视图函数,HttpRequest
    # 2.进行url配置,建立url地址和视图的对应关系
    # http://127.0.0.1:8000/index
    def index(request):
        # 进行处理,和M和T交互
        return HttpResponse("老铁,没毛病!")
    
    

    视图函数必须有一个参数request,进行处理之后,需要返回一个HttpResponse的类对象,hello python就是返回给浏览器显示的内容。

    2)进行url配置

    img

    ​ url配置的目的是让建立url和视图函数的对应关系。url配置项定义在urlpatterns的列表中,每一个配置项都调用url函数。

    url函数有两个参数,第一个参数是一个正则表达式,第二个是对应的处理动作。

    配置url时,有两种语法格式:

    a) url(正则表达式,视图函数名)

    b) url(正则表达式,include(应用中的urls文件))

    工作中在配置url时,首先在项目的urls.py文件中添加配置项时,并不写具体的url和视图函数之间的对应关系,而是包含具体应用的urls.py文件,在应用的urls.py文件中写url和视图函数的对应关系。

    由于使用的是django2.2.3版本,所以路由执行path函数

    """django_practice URL Configuration
    
    The `urlpatterns` list routes URLs to views. For more information please see:
        https://docs.djangoproject.com/en/2.2/topics/http/urls/
    Examples:
    Function views
        1. Add an import:  from my_app import views
        2. Add a URL to urlpatterns:  path('', views.home, name='home')
    Class-based views
        1. Add an import:  from other_app.views import Home
        2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
    Including another URLconf
        1. Import the include() function: from django.urls import include, path
        2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
    """
    

    看上面解释有三种使用方式

    第一种 基于函数的views:

    from my_app import views
    path('', views.home, name='home')
    

    第二种 基于Class的views:

    from other_app.views import Home
     path('', Home.as_view(), name='home')
    

    第三种 包含urls

    from django.urls import include, path
    path('blog/', include('blog.urls'))
    

    2.6.2 url匹配的过程

    在项目的urls.py文件中包含具体应用的urls.py文件,应用的urls.py文件中写url和视图函数的对应关系。

    img

    当用户输入如http://127.0.0.1:8000/aindex时,去除域名和最前面的/,剩下aindex,拿aindex字符串到项目的urls文件中进行匹配,配置成功之后,去除匹配的a字符,那剩下的index字符串继续到项目的urls文件中进行正则匹配,匹配成功之后执行视图函数index,index视图函数返回内容hello python给浏览器来显示。

    应用模块里面的urls.py

    from django.conf.urls import url
    from django.urls import path
    from booktest import views
    
    # 通过url函数配置url路由配置项
    urlpatterns = [
        path(r'index/', views.index)  # 函数映射路由
    ]
    

    项目里面的urls.py

    
    from django.contrib import admin
    from django.urls import path, include
    
    # 项目的urls文件
    # /index
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path(r'', include('booktest.urls')), # 包含booktest模块的urls
    ]
    
    

    2.7 模板

    模板不仅仅是一个html文件。

    2.7.1模板文件的使用

    1) 创建模板文件夹

    2) 配置模板目录 在settings.py文件中

    img

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # 项目目录的绝对路径
    
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],   # 设置模板文件目录
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
    1.  使用模板文件
      

    ​ a) 加载模板文件

    去模板目录下面获取html文件的内容,得到一个模板对象。

    def index3(request):
        return my_render(request, 'booktest/index.html', {'context': 'hello world'})
    
    def index4(request):
        return render(request, 'booktest/index.html', {'context': 'hello world'})
    
    def my_render(request, template_path, context_dict):
        '''使用模板文件'''
        # 1.加载模板文件, 模板对象
        temp = loader.get_template(template_path)
        # 2.定义模板上下文:给模板文件传递数据
        context = RequestContext(request, context_dict)
        # 3.模板渲染:产生标准的html内容
        res_html = temp.render(context_dict)
        # 4.返回给浏览器
        return HttpResponse(res_html)
    
    
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>模板文件</title>
    
    </head>
    <body>
            <h1>这是一个模板文件</h1>
    {{ context }}
    </body>
    </html>
    

    ​ b) 定义模板上下文

    向模板文件传递数据。

    ​ c) 模板渲染

    得到一个标准的html内容。

    img

    2.7.1 给模板文件传递数据

    模板变量使用:{{ 模板变量名 }}

    模板代码段:{%代码段%}

    for循环:

    {% for i in list %}

    {% endfor %}

    2.8 案例完成

    编码之前的准备工作:

    1) 设计出访问页面的url和对应的视图函数的名字,确定视图函数的功能。

    2) 设计模板文件的名字。

    以下为案例中的简单设计过程:

    1)完成图书信息的展示:

    a) 设计url,通过浏览器访问 http://127.0.0.1:8000/books/ 时显示图书信息页面。

    b) 设计url对应的视图函数show_books。

    查询出所有图书的信息,将这些信息传递给模板文件。

    c) 编写模板文件show_books.html。

    遍历显示出每一本图书的信息。

    1. 完成点击某本图书时,显示出图书里所有英雄信息的页面。

    a) 设计url,通过访问http://127.0.0.1:8000/数字/时显示对应的英雄信息页面。

    这里数字指点击的图书的id。

    ​ b)设计对应的视图函数detail。

    ​ 接收图书的id,根据id查询出相应的图书信息,然后查询出图书中的所有英雄信息。

    b) 编写模板文件detail.html。

    ------------恢复内容结束------------

  • 相关阅读:
    Swift
    Swift
    Swift
    Swift
    Swift
    Swift
    Swift
    将Ojective-C代码移植转换为Swift代码
    Swift
    房费制——报表(1)
  • 原文地址:https://www.cnblogs.com/myt2000/p/11947345.html
Copyright © 2011-2022 走看看