1122 django field attribute data manipulation operations orm

1. Static configuration files

1. By default all html files are placed in the templates folder

2. What is a static file

网站所使用到的提前写的css  js 第三方的前端模块,图片都叫做静态资源

Static resource files used for the site will all be on static folder 3. By default

手动创建static文件夹,根据静态资源分别创建子文件夹:
    通常情况下,在static文件夹内还会再见其他文件夹:

    css     文件夹
    js      文件夹
    font    文件夹
    img     文件夹
    Bootstrap
    fontawesome(图标库)
为了更加方便的管理文件

django中 需要你自己手动创建静态文件存放的文件夹
  • View function must have a return value, and return values ​​are HttpResponse object
  • URL the user enters in the browser to access to the appropriate resources, the premise is set up in advance of the back-end resource access interface, back-end did not offer appears 404

img

Access to a resource manual static files

  • django backend If you want to expose back-end resources, url must go inside to open the corresponding resource interface

    引入bootstrap时会报404找不到,需要去后端中配置
    settings文件中,最下面手动开设静态文件访问资源,手动添加以下代码
    
    # 将static文件里的所有资源都暴露给用户
    STATICFILES_DIRS = [
      os.path.join(BASE_DIR,'static')
    ]
STATIC_URL = '/static/'  # 访问静态文件资源接口前缀  通常情况下接口前缀的名字也叫static   (接口前缀叫什么,配置文件中也需要使用什么)

# 手动开设静态文件访问资源
STATICFILES_DIRS = [  # 静态资源所在的文件夹路径
    os.path.join(BASE_DIR,'static'),  # 将static文件里面所有的资源暴露给用户
    os.path.join(BASE_DIR,'static1'),  # 将static文件里面所有的资源暴露给用户
]
接口前缀会向STATICFILES_DIRS文件路径中查找路径文件夹,自上而下

img

Dynamic binding static files

{% load static %}
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
<script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
  • Tip: Clear your browser's cache pages used by district

    浏览器检查 -- settings -- Network -- Disable cache(禁止缓存)

    img

2.request method

2.1 request method

  • The default is to get a request form form

    Form to the form method = 'post', post request

    get请求也能携带参数,在url? 后面
    1.携带的数据不安全
    2.携带的数据大小会有限制
    3.通常只会携带一些不是很重要的数据
  • action = " "

    1.不写 默认朝当前地址提交
    2.只写后缀 /index
    3.写全路径 https://www.baidu.com
  • We submitted a request early post emergence towards the rear end of forbidden(403)the case you need to comment out the line in the configuration file content

    # 中间件
    MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
  • django default handling rear view function is get request is made whether get request or requests are performed post view function

    def login(request):
        print('来啦 老弟~')
        return render(request,'login.html')
    
get请求指向拿到login页面
post请求想提交数据  然后后端做校验 

2.2 Get request method front end

How to determine the current mode request

request.method

request.method 拿到的是字符串大写的请求方式 GET POST

def login(request):
    # if request.method == 'GET':
    #     print('来啦 老弟~')
    #     print(request.method,type(request.method))  # 获取前端请求方式
    #     return render(request,'login.html')
    # elif request.method == 'POST':
    #     print('post业务逻辑')
    #     return HttpResponse('收到了')
    if request.method == "POST":
        return HttpResponse('收到了')
    return render(request,'login.html')

2.3 request method

How to obtain the data submitted by the user's post, the front end of the rear end of the data are changed to obtain the string type

request.method

获取请求方式  并且纯大写的字符串

request.POST

获取用户提交的post请求数据
如何获取用户数据(******)
request.POST.get()  # 默认只会获取列表最后一个元素
request.POST.getlist()  # 如果你想获取列表 用getlist()

request.GET

获取用户提交的get请求数据
request.GET.get()  # 默认只会获取列表最后一个元素request.GET.getlist()  # 如果你想获取列表 用getlist()   

.get method

request.get方法默认只取列表的最后一个元素,
如果直接获取列表,使用get.list

3. pycharm connect to MySQL

Install the plug-in

img

Once connected, apply for confirmation.

The following:

img

4. django MySQL database connection

There must be two steps

4.1. Profile Configuration

settings configuration file to add the key DATABASES

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # 指定数据库类型
        'NAME': 'day49',  # 指定库的名字
        
        'USER':'root',  # 注意 键必须是全大写
        'PASSWORD':'',
        'HOST':'127.0.0.1',
        'PORT':3306,
        'CHARSET':'utf8'
    }
}

4.2. Specify database connection module

Do not take the initiative to tell django but with pymysql connection with the default mysqldb

  • You can project name in __init__.pythe writing
  • Also in the application name in __init__.pythe writing
import pymysql   
pymysql.install_as_MySQLdb()

5.django orm Profile

5.1 Basic Concepts

1. orm object-relational mapping

类               表对象         
数据对象点属性     字段对应的值

2. Why orm

能够让不会数据库操作的人也能够简单方便去操作数据库

3. drawback

封装程度太高  有时候会出现查询效率偏低的问题
所以工作中
    简单的用orm
    复杂的 追速度 需要你手动书写sql语句

5.2 django orm operation

书写模型类
去应用下的models.py中书写模型类(就是类)
  • After the time to write a django django project would correspond to a database
  • Circumstances do not appear multiple projects using the same data (******)
  • When you do not specify the primary key is automatically created when a django called id field as the primary key
  • If they created, django does not create
  • django no default char field, but supports user-defined

1. The database migration (synchronous) command

After creating orm fields must perform a synchronization command

1.python3 manage.py makemigrations

记录操作: 将数据库的修改 记录到小本本上(migrations文件内)

2.python3 manage.py migrate

操作执行: 将修改操作真正的同步到数据库中
  • The above command must occur simultaneously
  • Just modify the models inside the code associated with the database you have to re-run the above two commands

After you create a table

img

Table 2. Class deletions model change search field

Modify the field

直接修改代码,然后执行数据库迁移命令即可

Add field

models.IntegerField()   执行迁移命令
注意设置默认值
    # 方式1  设置默认值
        email = models.EmailField(default='[email protected]')  # varchar
    # 方式2   允许字段为空
        phone = models.BigIntegerField(null=True)
    # 直接在提示中给默认值
        gender = models.CharField(max_length=32)

img

Delete field

直接注释掉对应的字段 然后再执行数据库迁移命令即可(谨慎使用)

3. CRUD model table data

Query data.filter()

data = models.User.objects.filter(username=username)  

print(data)     # <QuerySet [<User: User object>]>
  • The results filter returns a "list", which is the real data objects
  • You can put multiple keyword parameters within parentheses filer which more keywords in the query parameters when the relationship is and

All data queries.all() *

user_list = models.User.objects.all()  # models.User.objects.filter()

"""
结果是一个"列表" 里面是一个个的数据对象
"""

The value

Support index value, but recommended .first()method value

支持切片,但不支持负数

Increased data.create()

create method will return a return value is the current value of the object itself is created

user_obj = models.User.objects.create(username=username,password=password)
print(user_obj,user_obj.username,user_obj.password)

Change Data.update()

.filter().update()

models.User.objects.filter(id=edit_id).update(username=username,password=password)
        """
        批量操作  会将filter查询出来的列表中所有的对象全部更新
        """

delete data.filter().delete()

Batch operation will filter check out the list of all delete all objects

models.User.objects.filter(id=delete_id).delete()
"""
批量操作  会将filter查询出来的列表中所有的对象全部删除
"""

to sum up

  1. Creating app need to register in the app settings
INSTALLED_APPS
    'app01'
  1. The Three Musketeers
    1. render the front page
    2. HttpResponse () commit a string
    3. redirect () Redirection
  2. cmd need to add the path settings in the TEMPLATES When creating app
'DIRS': [os.path.join(BASE_DIR, 'templates')]
  1. By default, all html files are placed in the template folder

  2. Static file: website written in advance css, js, third-party modules, images are called static files

  3. Static files on the site to use all default static folder, inside the folder based on the needs of different sub-directory store again

  4. Manually create a static folder to bootstrap into the folder, and import

  5. Open interfaces, the static resource file import, settings in the bottom, add manualSTATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ]

  6. Static files Dynamic Binding

    {% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
    <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
    
  7. Change the form's data submission form post

  8. Early submission of the request appears toward the rear end of the post 403, the need to go to settings file registered in a row of data

    MIDDLEWARE
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        # 'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    
  9. .methodThe method of obtaining the request mode (uppercase POST or GET)

  10. Mysql configuration connection embodiment django

    settings中DATABASES中添加连接端口
    'ENGINE': 'django.db.backends.mysql',更改
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'day50',    # 指定库的名字
            'USER':'root',      # 注意键全大写
            'PASSWORD':'',
            'HOST':'127.0.0.1',
            'PORT':3306,
            'CHARSET':'utf8'
        }
    }
    

    Change link library

    在项目名中的__init__中添加
    应用名中的__init__中添加
        import pymysql
        pymysql.install_as_MySQLdb()
    
  11. Database migration instruction

    python manage.py makemigrations # 记录操作
    
    python manage.py migrate        # 操作保存
    
  12. As long as the code is modified models in the database associated with the bullets, you must re-execute two commands

  13. charField field must specify the parameters max_length

  14. New field set default values

    1. Tag set default =
    2. That the default is an empty null = true
    3. After being given a default value is selected from an input

Guess you like

Origin www.cnblogs.com/fwzzz/p/11925103.html