python之django

Django 是根据比利时的爵士音乐家Django Reinhard命名

1.django框架流程图

python之django

2.django框架项目结构图

python之django

 

3.django框架应用目录结构

APP名称/
migrations 数据库操作记录->相应表结构发生变化,比如说字段类型,并不是增删改成的变动
admin Django 为我们提供的后台管理
apps 配置当前APP
models ORM,写指定的类通过命令可以创建数据库结构.
tests 单元测试
Views 业务逻辑代码

正序分析,倒序开发

 

 

前端设计html给后端改

django
 1、mvc模式:
    models模型
    views视图
    controller控制器
2、django mvt模式
    models模型
    views视图 (controller控制器)
    templates模板
3、django的工作原理
    用户发送请求---------(http://www.163.com)----------->在django urls.py中找对应的地址-------->在django views中找对应的方法 ----------->处理models的操作--------->逻辑控制--------->在templates找到相应的视图模板 ---------->显示给用户处理结果视图
4、django的安装

4.1安装django
    pip3 install django

4.2安装mysqldb

在 python2 中,使用 pip install mysql-python 进行安装连接MySQL的库,使用时 import MySQLdb 进行使用

在 python3 中,改变了连接库,改为了 pymysql 库,使用pip install pymysql 进行安装,直接导入即可使用

但是在 Django 中, 连接数据库时使用的是 MySQLdb 库,这在与 python3 的合作中就会报以下错误了

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'

解决方法:在 __init__.py 文件中添加以下代码即可。

import pymysql
pymysql.install_as_MySQLdb()

4.3创建数据库:create database databasename default charset=utf-8


5、django的项目创建

5.1创建django的项目: 执行命令:django-admin startproject 项目名称

[email protected]:#django-admin startproject mypro

5.2创建django的应用:进入到项目目录mypro,执行命令django-admin startapp 应用名称

[email protected]:#cd mypro
[email protected]:#django-admin startapp testdjango

#目录结构

[email protected]:~/django0923/mypro$ ls
manage.py  mypro  testdjango

5.3修改~/mypro/mypro中的settings.py,以新增应用、连接数据库、设置模板
5.3.1  新增应用

    INSTALLED_APPS={
            运用名称
        }

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'testdjango'
]

5.3.2  连接数据库
        DATABASES={
        }
        将 ‘ENGINE'改成mysql
        'HOST'大写,数据库服务器的名称
        'PORT'大写,数据库服务器的端口  3306
        'USER'大写,数据库服务器的登陆名 root
        'PASSWORD'大写,数据库服务器的密码
        'NAME'大写,数据库服务器的数据库名

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST':'127.0.0.1',
        'PORT':3306,
        'USER':'root',
        'PASSWORD':'root',
        'NAME':'testdjango'
    }
}

5.3.3  模板的设置:
        设置模板的路径 在项目文件夹的settings.py
        在TEMPLATES={    }
        DIRS里加模板的路径 os.path.join(BASE_DIR,'templates')

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',
            ],
        },
    },
]


5.4修改~/mypro/testdjango中的models.py,定义一个类,models的类与数据库的表相对应,

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models

# Create your models here.
class test_django(models.Model):
        name=models.CharField(max_length=20)# CharField相当于varchar(20)


5.5同步数据库:

           根据models.py产生数据库的表
            python3 manage.py makemigrations
            python3 manage.py migrate

[email protected]:~/django0923/mypro$ python3 manage.py makemigrations
#返回值
Migrations for 'testdjango':
  testdjango/migrations/0001_initial.py
    - Create model test_django

[email protected]:~/django0923/mypro$ python3 manage.py migrate
#返回值
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, testdjango
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... 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 auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK
  Applying testdjango.0001_initial... OK


5.6修改~mypro/mypro下的urls.py:        url(r'user/',views.index)

from django.contrib import admin
from django.urls import path
from testdjango import views#需要手动导入
from django.conf.urls import url#需要手动导入
urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'test_django/',views.index)
]

5.7修改在应用的目录下的views.py:

        return
                HttpResponse(”直接跟字符串")
                render(request,'网页',字典类变量)
        (1)返回HttpResponse
        (2)返回不带参的网页
        (3)返回带参的网页: user=UserInfo.objects.all()


5.7.1新增响应

         添加一个index方法:
            def index(request):request是参数
                return HttpResponse("ok");
                返回给浏览器的信息

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse#需要手动导入
# Create your views here.
def index(request):
        return HttpResponse('ok')

5.7.2新增模板

        注释掉新增的响应,新增以下代码
        def index(request):
            return render(request,'index.html')
            先把对象全部显示,引入UserInfo
                UserInfo.objects.all()相当于select * from userinfo
                定义一个字典类的变量
                context={'user':users}
                传入render参数中,
                return render(request,'index.html',context)

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import test_django#手动导入
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
#       return HttpResponse('ok')
        users=test_django.objects.all()
        context={'user':users}
        return render(request,'index.html',context)

5.8启动服务器: 执行这个django项目,登录网页:http://127.0.0.1:8000/test_django/
            在manage.py所在的目录下
                python3 manage.py runserver

[email protected]:~/django0923/mypro$ python3 manage.py runserver#服务器挂起
Performing system checks...

System check identified no issues (0 silenced).
September 29, 2018 - 09:21:49
Django version 2.1.1, using settings 'mypro.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

5.9与数据库连通:

5.9.1在数据库加入数据
        利用django的后台
            新建用户
                python manage.py createsuperuser
            在我们自己的表中填数据,先注册

[email protected]:~/django0923/mypro$ python3 manage.py createsuperuser
Username (leave blank to use 'zelin'): testdjango
Email address: [email protected]
Password:                     #a12345.12345
Password (again): 
Superuser created successfully.

5.9.2在/mypro/testdjango/admin.py从~/mypro/testdjango/models.py中导入类
                在应用下面的admin.py,导入一下models里面的类
                    admin.site.register(UserInfo)

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin
from .models import test_django#手动导入
# Register your models here.
admin.site.register(test_django)

 

5.10  新建tempplates目录,tempplates目下存放.html文件,即模板,模板内输出{{user}}

[email protected]:~/django0923/mypro$ mkdir tempplates
[email protected]:~/django0923/mypro$ ls
manage.py  mypro  tempplates  testdjango

最后修改模板,即html文件

                    在模板中直接输出{{}}
                    {{传入参数字典的键名}}
                    如果键是一个列表
                    for循环遍历
                    {% for u in user(键名) %}
                    {%endfor%}endfor是必须有一个停止的信息
                    中间输出对象的属性
                    {{u.username}}
                    {{u.password}}

<!DOCTYPE html>
<html>
        <head>
                <meta charset=utf8>
                <title>我的网页</title>
        </head>
        <body>
                <h1>这是我的网页</h1>
                <h3>{{user}}</h3>
                {% for u in user %}
                        <h3>{{u.username}}</h3>
                        <h3>{{u.password}}</h3>
                {% endfor %}
        </body>
</html>

      

5.11最后,修改models.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models

# Create your models here.
class test_django(models.Model):
#       name=models.CharField(max_length=20)
        username=models.CharField(max_length=20)
        password=models.CharField(max_length=20)

最后修改模板,即html文件

                    在模板中直接输出{{}}
                    {{传入参数字典的键名}}
                    如果键是一个列表
                    for循环遍历
                    {% for u in user(键名) %}
                    {%endfor%}endfor是必须有一个停止的信息
                    中间输出对象的属性
                    {{u.username}}
                    {{u.password}}

<!DOCTYPE html>
<html>
        <head>
                <meta charset=utf8>
                <title>我的网页</title>
        </head>
        <body>
                <h1>这是我的网页</h1>
                <h3>{{user}}</h3>
                {% for u in user %}
                        <h3>{{u.username}}</h3>
                        <h3>{{u.password}}</h3>
                {% endfor %}
        </body>
</html>


    5.12、额外加入数据
         python manage.py createsuperuser
        在admin.py里加入一句话
            admin.site.register(类名)
5.13、登陆后台
http://locahost:8000/admin

5.14、登录django

http://localhost:8000/testdjango