Django daily -1

Django daily -1

Django most commonly used in three things

Before we introduced the Django installation and creation, as well as its basic principle, then we will gradually introduce something inside Django common, three are usually used as a return value.

HTTPresponse

String to return

return HttpResponse('hello world~')

# 会返回一个字符串,即屏幕上只会剩下这一个字符串,用处比较有限,不过也算有用

render

To return a web page, this use is relatively large, such as

def reg(request):
    return render(request,'reg.html')
# request的用处我们在下面会介绍,这个例子的意思就是最终会返回一个reg.html网页,通常我们在浏览网页的时候,网页之间的切换也许会用到这个,也许不会,这只是一种选择.

redirect

Redirect the concept we introduced before the http protocol when introduced, so we define redirect, then you can go directly to the current web page after web page redirect.

def home(request):
    return redirect('https://baidu.com')
# 即在触发了这个函数之后就会直接跳向重定向的网页

Static related files

Static files are usually used website include the following categories, namely their own written JS, CSS written their own or third-party frameworks we have quoted, bootstrap, fontwesome, sweetalert and so on.

Before we learned that, at the time of the introduction of third-party framework, we can choose to use the online cdn cache files, or download it yourself, here we choose to use a static file with the local static files, then you need to put these static files unity in a folder inside, we would usually placed in a new folder called static, the convention, no reason.

But the point to note is that after we put all the static files are thrown into the folder, Django and not very accurate to identify the path, even if we use to refer to the root directory of the files in html interface does not work, Django I can not find itself, so we have to look at the configuration path

Configuring access to resources are static files in the root directory of the settings.pyfile, in the end we will see

# settings.py文件的最下方

STATIC_URL = '/static/' 
# 这是我们访问静态资源的接口前缀,很重要,就是我们输网址的时候要写的接口前缀
# 然后我们需要在这个语句下面加上这样一个配置项
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),  # 拼接路径名
]

After adding a good path, we introduce ways html file also needs to be changed, as follows:

# **.html文件,<head>在这里面添加以下语句</head>

{% load static %}
<link rel="stylesheet" href="{% static '静态文件所在地址'%}">

# 这样都配置过之后,我们才能正确的引入这些静态文件,并正确引用他们.

form form get and post

Forms are familiar form the front end when we learned that follows the standard format

<form action="" action="" method="post">
# action参数可以写的是:
    1. 空着,会默认向当前页面的地址提交
    2. 只写后缀,如/index,/admin等,则会在前面自动拼接上当前的网址和端口,然后拼接上所写的后缀
    3. 写全路径
# method参数,默认是get,还可以写post
    我们要知道这两者的区别,get,当我们输入网址,进入网址的时候,此时服务端是已经收到了一个get请求的,所以我们才能接收到一个网页,这个网页就是服务端对于我们的get返回的一个返回值,但是get请求本身是有一些问题的,主要体现在以下两点:
    1. get请求不安全,因为get请求在携带参数的时候是直接在url?后面添加的,比如?username=admin&password=159789
    所以这种情况下,如果是输入的账号密码然后发送一个get请求,是非常不安全的
    2. get请求所能携带的参数是有长度限制的,根据每个浏览器的不同,都会有不同长度的限制
    
    
# 在了解了以上内容之后,如果我们想要提交post请求,除了把method里面参数改成post之外,还需要注释掉一个语句,这个语句对于我们初学者来说没有用处,还会影响整个项目的运行.
# 其位置仍然在settings.py文件里,我们需要注掉的就是'django.middleware.csrf.CsrfViewMiddleware'这个语句
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',
]

Magical request

We write requests are views each method is going to be passed in parentheses parameters, its biggest role is responsible for the interaction of the front and back-end data, the front-end back-end received almost all from the requests in, request a an object, and is a very comprehensive and powerful object, the object we can point out a lot of things, such as:

request.MATE

# mate所包含的是几乎所有的HTTP的请求信息,以k:v键值对的形式存储的

request.scheme
# 请求的方式,可能性是两种,即http和https

request.path
# 请求的路径,这里是低昂对路径,如果要取绝对路径是request.get_full_path()
request.encoding
# 获取提交的数据的编码方式
request.session
# 获取是一个session,实际上就是一个无序的字符串,用来作为唯一识别吗的,因为之前我们说过http是一个无状态的协议,需要另外的东西来确保用户的状态
request.cookies
# 与session非常相似的一个东西,区别就在于session在服务端,cookies在客户端
request.method
# 获取请求方式,GET或者POST
request.body
# 请求的主体,返回数据的格式是一个字符串
request.data
# 请求的数据部分,和body相似,但是格式不同,data是一个字典对象
request.POST
# 获取POST请求所携带的数据,可以直接当成一个列表套字典来取值,但是仅仅用request.POST.get()只能取到列表的最后一位,如果要取整个列表的话需要用request.POST.getlist()来取值
request.GET
# 用法和POST几乎一样,就是获取GET()请求所携带的数据

By value templates

def reg(request):
    user_dict = {'name': 'jason', 'pwd': 123}
    # 给模板传值的方式1
    return render(request, 'reg.html', {'xxx': user_dict})      # 会将user_dict传递给reg.html页面,页面上通过xxx就能拿到该字典

    # 给模板传值的方式2
    return render(request, 'reg.html', locals())  # 会将当前名称空间中所有的变量名全部传递给页面
    # locals()会出现效率问题,变量名很多的话,会造成空间浪费,不过个人学习的话,其实直接用locals()没什么问题

Django connect to the database and its powerful ORM

We know that it can be used as a database server, we can use Navicat to connect to the database, can be directly used cmd window to operate the database, the same, we can also connect to the database by Django, and its operation

Preparation Django database connection

  1. First we need to write information to connect to the database in Django's configuration file
DATABASES = {
                    'default': {
                    'ENGINE': 'django.db.backends.mysql',  # 指定数据库MySQL,postgreSQL
                    'NAME': 'db1',          # 使用哪个库
                    'USER': 'root',         # 数据库账号
                    'PASSWORD': 'root',     # 数据库密码
                    'HOST': '127.0.0.1',    # 数据库的地址
                    'PORT': 3306,           # 数据库的端口
                    'CHARSET': 'utf8'       # 数据库的默认字符编码
                                }
                    }
  1. The database is used by default Django musqldb, but now this tool is almost out of print, so we need to tell Django not to use mysqldb, but with pymysql to connect to the database, where there are two common methods

    • In Django project name __init__.pyis written in the following statement
    • Django's name in the app __init__.pywrite the following statement in
    import pymysql
    pymysql.install_as_MySQLdb()

ORM statement creates table

Inside the Django ORM can help us create the table, but can not directly create the database, so we must first manually create the database, then create a table by ORM.

First we need in the app name modelswritten inside needs to be added into the database table, including the various fields, the routine is as follows:

from django.db import models

# Create your models here.
class Userinfo(models.Model):
    # 设置id字段为Userinfo表的主键,id int primary key auto_increment
    # django里面可以不指定主键字段,django的ORM会自动给当前表新建一个名为id的主键字段
    id = models.AutoField(primary_key=True)
    # 设置username字段, username varchar(64) CharField必须要指定max_lenth参数
    # django 的ORM中,没有char字段,但是django暴露给用户可以自定义char字段
    username = models.CharField(max_length=64)
    # 设置password字段, password int
    password = models.IntegerField()
    phone = models.BigIntegerField(default=110)  # 新增的字段可以提前设置默认值,如果没有提前设置,那么一定要设置可以为null,否则不让你添加字段
    addr = models.CharField(max_length=64, null=True)  # 该字段可以为空


class Book(models.Model):
    title = models.CharField(max_length=64)

After the above definition of a good class, we will be able to actually create the tables in the following two statements

# 以下两个语句是在cmd窗口,或者说是在Pycharm里面的Terminal窗口里输入的,注意当前目录,一定要在项目所在的位置
python manage.py makemigrations #不会创建表,仅仅是生成一个记录,将你当前的操作记录下来(migrations文件夹)
python manage.py migrate  #真正的将你的ORM语句迁移到数据库中
        
# 尤其要注意的是:只要在models.py中修改了跟数据库相关的代码,就必须重新开始执行上面两个语句,注意,必须重新执行!!!

ORM statement simple operation of the database

Here are two simplest, which are inserts and queries

insert

models.Userinfo.objects.create(username='admin', password='123')
# 上述语句实现的就是这个sql语句:insert into userinfo(username,password) values('admin','123');
# create方法会有一个返回值,返回值就是当前被创建的数据对象
# 这里要注意的是,你要清除的知道自己插入的表的字段的数量,以及格式,否则很容易报错

Inquire

# 1. get() 当查询条件不存在的时候会直接报错,如果存在会直接给你返回数据对象本身(不推荐使用)
res = models.Userinfo.objects.get(username=username)  # select * from userinfo where username = 'jason'
print(res)
print(res.username, res.password)

# 2. filter() 查询
  # 当条件存在的情况下,无论数据有几条,返回的都是列表套对象的数据格式
  # filter可以放多个查询条件,并且是and关系
  # filter查询出来的结果当做列表去对待,支持正数的索引取值和切片,不支持负数,所以不能用[-1]
res = models.Userinfo.objects.filter(username=username, password=password)
# user_obj = res[0]
user_obj = res.first()  # 取queryset第一个元素

Guess you like

Origin www.cnblogs.com/Xu-PR/p/11716018.html