Python3 Django的基本使用

Python3 Django的基本使用

本文由 Luzhuo 编写,转发请保留该信息.
原文: http://blog.csdn.net/Rozol/article/details/79526163

以下代码以Python3.6.1为例
Less is more!
Python 3.6.1
Django 2.0.2
Django学习文档: http://python.usyiyi.cn/translate/django2/index.html
项目名:Django_base; 应用名:booktest
步骤: 创建虚拟环境 -> 安装Django -> 创建项目 -> 创建应用

简介

  • Python的Web开发框架
  • Django采用MVT设计框架
    • M: 模型model, 数据库交互
    • V: 视图view, 接收请求, 处理数据, 返回结果
    • T: 模板template, 呈现内容给浏览器
    • 框架设计思想与MVC相同, MVC中的V, C分别对应MVT中的T, V.

Django

  • 创建项目:
    • cd到要创建项目的文件夹
    • 创建: django-admin startproject [项目名]
    • 目录说明:!
      • manage.py: 与Django交互的方式
      • settings.py: 配置信息
      • urls.py: URL
      • wsgi.py: 与WSGI兼容的Web服务器入口
  • 创建应用
    • cd 到项目(Django_base)目录
    • 运行: python manage.py startapp [应用名]
    • 目录结构:
      • migrations # 数据迁移
      • admin.py # 管理
      • models.py # 模型模块
      • tests.py # 测试模块
      • views.py # 视图模块

模型M(M)

  • 通过模型类完成与数据库的交互
  • 配置数据库

    • settings.py

      DATABASES = {
          'default': {
              'ENGINE': 'django.db.backends.sqlite3',
              'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
          }
      }
      
  • 编写模型

    • 打开应用 models.py

      • 编写模型代码:

        from django.db import models
        
        ''' Bookshelf书架: 分类shelf_type 书架号shelf_id BookInfo书信息: 名称bname 添加日期btime 分类btype '''
        
        # 继承models.Model才能作为模型取用
        
        class Bookshelf(models.Model):  # 表
            # 字段类型:
            # CharField(String)
            # IntegerField(int)
            # DateTimeField(Time)
            # BooleanField(Boolean)
            # ForeignKey(外键)
        
            # id不用写, 自动添加的
            shelf_type = models.CharField(max_length=10)
            shelf_id = models.IntegerField()
        
            def __str__(self):
                return self.shelf_type
        
        class BookInfo(models.Model):
            bname = models.CharField(max_length=20)
            btime = models.DateTimeField()
            btype = models.ForeignKey(Bookshelf, on_delete=models.CASCADE)
        
            def __str__(self):
                return self.hname
  • 数据迁移

    • 注册应用
      • 打开项目 settings.py
        • INSTALLED_APPS = [] 中添加 booktest[应用名]
    • 生成迁移: python manage.py makemigrations
    • 执行迁移: python manage.py migrate
  • 测试数据库

    • 进入: python manage.py shell
    • 测试:

      from booktest.models import *
      from datetime import datetime
      
      bs = Bookshelf()
      bs.shelf_type = 'T工业技术'
      bs.shelf_id = 12345
      bs.save() # 添加
      
      Bookshelf.objects.all() # 查询所有信息
      
      bs = Bookshelf.objects.get(pk=1) # 查询指定信息
      bs.shelf_type
      
      bs.shelf_id = 56789
      bs.save() # 修改信息
      
      bs.delete() # 删除指定信息
      
  • 注册模型(让服务器能对数据进行增删改查)

    • 打开: ‘admin.py’

      from .models import *
      admin.site.register(BookInfo)
      admin.site.register(HeroInfo)
      
    • 启动服务器: 见 服务器

视图V(C)

  • 配置root页面

    • 打开 settings.py
    • 找到 ROOT_URLCONF = 'Django_base.urls'
    • 打开 Django_base[项目名].urls.py
      • 导入 from django.urls import include, path
      • urlpatterns 添加 path('', include('booktest.urls')),
    • 在booktest[应用名]下创建: urls.py 文件

      • 书写以下内容

        from django.urls import path
        from . import views
        
        urlpatterns = [
            path('', views.index),
            path('<int:question_id>', views.show)  # 接收数字id
        ]
  • 接收返回

    • 打开: views.py (复杂使用见模板)

      from django.http import *
      
      def index(request):
          return HttpResponse("hello world")
      
      def show(request, question_id): # 接收参数数字id
          pass

模板T(V)

  • 创建模板

    • 创建文件夹
      • 在项目(Django_base)下创建: templates
      • 在templates下创建: 应用同名文件夹(booktest)
    • 添加模板
      • 右键创建html文件: ‘index’
    • 配置模板:

      • 打开 settings.py

        • 修改:

          TEMPLATES = [
              {
                  'DIRS': [os.path.join(BASE_DIR, "templates")],
              }
          ]
          
  • 使用模板

    • 打开: views.py

      from django.template import RequestContext, loader
      from django.shortcuts import render
      
      def index(request):
          # 方式一
          temp = loader.get_template('booktest/index.html')  # 加载模板
          return HttpResponse(temp.render())  # 渲染模板并返回
          # 方式二√
          return render(request, 'booktest/index.html')
    • 向模板传送内容:

      • html:

        <body>
        <h1>python</h1>
        <h2>{{ title }}</h2>
        
        <ul>
        {% for book in list %}
        <li>{{ book.btitle }}</li>
        {% endfor %}
        </ul>
        
        </body>
      • python:

        
        # --- 向模板传内容 ---
        
        
        # <h2>{{ title }}</h2>
        
        context = {'title': 'hello'}  # {{输出}}
        
        
        # {% for book in list %}
        
        bookList = BookInfo.objects.all()  # 从模型取数据
        context = {'list': bookList}  # {%执行python代码%}
        return render(request, 'booktest/index.html', context)

服务器

  • 创建管理员账号:
    • python manage.py createsuperuser
  • 本地化:
    • 打开: settings.py
      • 语言:
        • 修改: LANGUAGE_CODE = 'zh-hans'
      • 时区:
        • 修改: TIME_ZONE = 'Asia/Shanghai'
  • 运行项目:
    • python manage.py runserver 80
  • 管理界面:
    • 进入: http://127.0.0.1/admin
  • 自定义管理界面:

    • 打开: admin.py
    • 默认模板注册: admin.site.register(Bookshelf)
    • 自定义模板:

      
      # 方式二
      
      @admin.register(Bookshelf)
      class BookshelfAdmin(admin.ModelAdmin):
          # --- 列表页 ---
          # 显示字段
          list_display = ['id', 'btitle', 'bpub_date']
          # 过滤字段
          list_filter = ['btitle']
          # 搜索字段
          search_fields = ['btitle']
          # 分页
          list_per_page = 10
      
          # 操作选项显示位置
          actions_on_top = True  # 页头(默认True)
          actions_on_bottom = True  # 页尾(默认False)
      
      
          # --- 添加/修改页 ---
          # 属性的先后顺序
          # fields = ['bpub_date', 'btitle']
          # 属性分组
          fieldsets = [
              ('base', {'fields': ['btitle']}),
              ('super', {'fields': ['bpub_date']})
          ]
      
      
      # 方式一
      
      
      # admin.site.register(Bookshelf, BookshelfAdmin) # 注册
      
    • 关联

      class BookInfoInline(admin.TabularInline):  # StackedInline堆叠, TabularInline表格
          model = BookInfo
          extra = 3  # 额外添加几个数据
      
      class BookshelfAdmin(admin.ModelAdmin):
          # --- 添加页 - 关联 ---
          # 关联对象, 添加一个BookInfo时可添加多个HeroInfo
          inlines = [BookInfoInline]
      
      admin.site.register(Bookshelf, BookshelfAdmin) # 注册
    原文作者:LZ_Luzhuo
    原文地址: https://blog.csdn.net/Rozol/article/details/79526163
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞