The second: Django custom login function

Custom login feature

Create a static folder (static folder)

views.pyView function is created, you will need to use some style css and js objects, or if the CDN to accelerate the way through, from the network calls will become unsafe, when the server network failure, can lead to style css and js object loads It does not come out, so we need these static files into local storage.

Static files

css files, js files, images, fonts, as well as some third-party frameworks (bootstrap, sweetalert, fontawesome)

Static folder (static)

Decoupling, easy maintenance and management.

In response to these static files, we need to create a special folder, so you can not look very messy, can be unified management, we will name the general static, structured as follows:

static
    - css      网站用到的所有css文件
    - js       网站用到的所有js文件
    - image    网站用到的所有图片文件
 
    第三方文件

django static configuration file

basic configuration

Modify settings.py in:

STATIC_URL = '/static/'  # 访问后端静态资源的接口前缀  默认情况下接口前缀名与静态文件名保持一致
        """
        <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
        你要想访问后端的静态资源 你必须以接口前缀开头 后面跟上具体的文件路径 才能够访问到对应的资源
 
        当你的接口前缀正确之后  会拿着后面的路径依次去下面列表中的每一个文件夹下查找对应的资源
        顺序是从上往下依次查找 如果都没有找到才会报错
        """
STATICFILES_DIRS = [
            os.path.join(BASE_DIR,'static'),  # 这里的static才是你文件夹的路径
            os.path.join(BASE_DIR,'static1'),
            os.path.join(BASE_DIR,'static2'),
        ]
# 当static和static1中都有一个a.txt,当在static中查找到之后,就不会再去static1中查找了。

STATIC_URL: static resource access back-end interface prefix, prefix the interface with the static default file names consistent

It acts like a token, when you want to access static web resources, one must write on here '/static/', when recognizing href path (link in <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap. min. css">) or script in the src path ( <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>) begins with static, django will allow you to STATICFILES_DIRSlist All files that exist in that folder, find the required resources.

When the path prefix changed to XXX, prefix interface that also needs to be changed XXX.

Thus, static here is the path corresponding to the beginning of static.

Static resource dynamic binding

Static resource interface foregoing, once the change, it is necessary to modify the css html introducing path and prefix js, this will be very troublesome when high html, requires a lot of time to modify, thus creating a dynamic binding Methods:

{% 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>
 

When the static resource interface modifications, css and js path will change.

post request to modify configuration files

When submitting post requests, you need to go to the configuration file comment out the line:

# 中间件
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',
]

form Form Review

The default is to get a request form form to submit data, with the data submitted to the back url ?xxx=yyy&zzz=tttexisting form.

http://127.0.0.1:8000/login/?username=admin&password=123

Mode acquisition request request.method( )

To reduce the level of code: function processing view get more requests can be directly re-write function in vivo to the corresponding logical get request, using a request requesting the other general method to distinguish.

def login(request):
    if request.method == 'POST':
           username = request.POST.get('username')
        password = request.POST.get('password')
        return httpresponse('收到了')
return render(request,'login. html')

request object methods

request.method: Acquisition request, the return GET / POST

request.POST: Get in line with data POST request carries the return of a large dictionary. ( <QueryDict: {'username': ['admin'], 'password': ['123']}>)

  • request.Post.get('key'): Take only the last element of the list

  • request.POST.getlist('key'): Remove the entire list

request.GET: Get in line with data get request carries data format ( url?xxx=xxx&ooo=lll)

  • request.GET.get('key') : Take only the last element of the list
  • request.GET.getlist('key') : Remove the entire list

djangoMySQL connection ★

1. go profile (the settings.py) related parameter configuration

# 修改数据库的配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # 数据库类别
        'NAME': 'day49',  # 库的名字
        'HOST': '127.0.0.1',
        'PORT': 3306,
        'USER': 'root',
        'PASSWORD': '123',
        'CHARSET': 'utf8'
    }
}

2. In the Project name or application name the following __init__file, specify the use of alternative pymysql mysqldb connection mysql

import pymysql
 
pymysql.install_as_MySQLdb()

django orm Profile

django orm do not create a library, you can only create a table

# orm对象关系映射:
类   ------> 表
对象  ------> 记录
属性  ------> 字段值

orm python allows us to use object-oriented syntax (dot character) to simple and quick operation data

Writing first need to go to the class model (model table) corresponding to the models.py under application

# 示例:
class User(models.Model):
    # int类型 primary key主键 auto_increment自增长
    id = models.AutoField(primary_key=True)
    # varchar(32)类型的字段,限制展示长度为32
    name = models.CharField(max_length=32)
    # int类型的字段
    password = models.IntegerField()
    # 其实创建的还是varchar类型
    email = models.EmailField(default='[email protected]')
    # hobby字段可以为空
    hobby = models.CharField(null=True,max_length=32)

After the need to perform database migration command:

*************************数据库迁移(同步)命令************************
python3 manage.py makemigrations  # 仅仅是将你对数据库的改动记录到某个小本本上(migrations文件夹)
python3 manage.py migrate  # 将改动真正的同步到数据库中
 
***********只要你动了models.py跟数据库相关的代码 你就必须要重新执行上面的两条命令来保证数据库与models.py一致***********

Deletions change search field

By field

New fields in the direct model table models.py file, then you can perform a database migration command

  • Field is set to the default value
    • models.EmailField(default='123456@com')
  • Run this field can be empty
    • models.EmailField(null=True)

Search field

....

Change field

After modifying the code models.py file, you can perform a database migration command

Delete fields

As long as the comment out the corresponding fields, then perform a database migration command will delete all the data fields and the corresponding information (caution)

Deletions data change search

check

1, a single query data

from app01 import models   # 先导入models模型表
models.类名.objects.filter(字段名='字段值')
res = models.User.objects.filter(username='jason')  # select * from user where username='jason'
# 返回的结果是一个列表  支持索引取值但是不支持负数并且不推荐使用 推荐你使用它给你封装好的方法
user_obj = res.first()  # 取上面返回的列表中的第一个值
# filter方法条件不存在的时候 不会报错返回的是一个空列表
 
"""
filter括号内直接放多个关键字参数 并且多个关键字参数之间是and关系
res = models.User.objects.filter(username='jason',password='123')
# 类似执行select * from user where username='jason' and password='123';
"""

2, all of the data query

  • filter () is not written to take all brackets
  • all () to query all data

Query data, it returns a list of similar sets of data dictionary

<QuerySet [<User: jason>, <User: egon>, <User: sean>, <User: admin>, <User: 你不行>]>

increase

1、create()

user_obj = models.User.objects.create(**kwargs)
 
user_obj = models.User.objects.create(name=username,password=password)
print(user_obj,user_obj.name)
 
# 该方法有返回值,返回值就是当前被创建的对象本身

2, binding method object

# 先生成一个User对象
user_obj = models.User(name=username, password=password)
 
# 调用对象的绑定方法
user_obj.save()

delete

models.User.objects.filter(id=delete_id).delete()
 
# 将filter过滤出来的数据全部删除,类似批量删除

change

1, Mode 1 (recommended)

models.User.objects.filter(id=edit_id).update(name=username, password=password)

2. Second way (to know, not recommended)

By binding method for assigning objects and object

# 先获取数据对象
edit_obj = models.User.objects.filter(id=edit_id).first()
 
# 再修改对象属性
edit_obj.name = username
edit_obj.password = password
 
# 调用对象的绑定方法保存
edit_obj.save()
 
# 该方法会将所有的字段的数据重新修改,并不是针对某个字段进行修改,不推荐。

Guess you like

Origin www.cnblogs.com/cnhyk/p/12168159.html