django entire process

The overall process to go again django 
        login function, for example 
            a static configuration file 
            form the back end how to get the form to submit data 
            request method 
            pycharm database connection mysql database using django 
            django orm Profile 
            CRUD table field 
            CRUD table data

A static configuration file

1. Create ready

Create a project, create APP, settings registered in the app, create templates and folders to register the settings file

INSTALLED_APPS = [
                'django.contrib.admin',
                'django.contrib.auth',
                'django.contrib.contenttypes',
                'django.contrib.sessions',
                'django.contrib.messages',
                'django.contrib.staticfiles',
                # 'app01'  # 简写
                'app02.apps.App02Config'  # 全称
            ]
app concept 
            django is actually designed to develop a web app framework of 
            an empty django project is similar to a university 
            app is similar to the various University inside 
            such as your elective system (students, teachers, administrators) 
            in for example, you Youku project (common user, vip user, administrator) 
            vernacular: for different functional modules you can open a different app to handle decoupling implement the program 
            and achieve better development group    

 

2. Create route

 

 

 3. Create a view function

 

 

 4. Write the template file

The files are usually used website html templates are placed in a folder under
static resources are usually used website on the static folder

 

 

 Startup project:

Users can access all resources in the url (******)

The browser has been able to enter the URL to access the corresponding resource, because the back-end interface to offer access to resources (url),
Django can open interfaces ??? where interfaces are in urls.py correspondence between routing and view function


Back-end resources generally need to manually specify whether exposed to the user, because there is no static exposure to the user, the browser can not access resources,
it stands to reason that we should be in the urls file to the folder configured static routing
but gives us a better django way, only you need to configure static path in the configuration file on it

5. Configure static routes (******)

For the preceding paragraph has been written document we just use it to take over these files can be called called " Static file " 
   1. Static files can be 
        bootstrap preceding frame has been written for a class of 
        images 
        CSS 
        JS 
   2. static files all on static default folder under 
        static default folder by default subfolders created folder 
            css folder of the current site all the style file 
            js file js file of the current site all 
            img files in the current site all the picture files 
            to other (front-end framework code third-party plug-in code ...)
Static configuration file

= STATIC_URL '/ static /' # static resources are only accessible interfaces prefix , in order to access static resources url must be based / static / beginning, back to keep the file path, and the following static meaning is not the same
STATICFILES_DIRS = [
  os.path .join (base_dir, 'static'), # folder , once you begin with a prefix based interfaces so the interface will automatically hold back the file path prefix to the list one by one folder (static, static1 ... ) Find files
  os.path.join (base_dir, 'static1'),
  os.path.join (base_dir, 'static2'),
]

 

 

 

 

 

 

 ps: Clear Cache

 

 

The default is to support automatic restart django code so you only need to refresh the page several times you can, but sometimes it's restart mechanism is relatively slow 
mechanism: real-time monitoring file changes as long as the code changes will automatically restart your code might not this time the error will automatically finish

6. Static file interface prefix "dynamic analysis"

Static file interface prefix originally / static / but if that leadership requires replaced / xxx / how to do it? Manually modify each html? So there are a thousand html file it? So we need to get moving
1. primeval
<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>

2.利用解析器,动态获取接口前缀
{% 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>
Static dynamic resolution file path 
            {%}% Load static 
            {% static "file path"%}

 

Second, the login page

1.html perfect (form form submission data)

form form submission data 
           1. Action 
                1. Do not write default towards the current url (http://127.0.0.1:8080/index/?id=1) submitted 
                2. Write only the suffix / index / or / index /? id = 1 
                3. write the full path (you want to submit this form data to url to other sites)       2. Method, 
                by default get a request, needs to be changed post 
          3. get request parameters and post request carries the characteristics of the 
                get request is beginning directly behind the url? & connect to multiple conditions 
                / index /? = ID. 1 
          

& username = Jason (get request carries parameter size is limited to) the requested data is on the post request body

 

Can be replaced by post request method 
requires settings to a file comment out after the intermediate post request into

 

 

 2. request data acquisition distal

form form data submitted by the destination of Action
         1 . By default, do not write to the current address submitted
         2. You can also write suffix / index / (used this project)
         3. Also you can write the whole path 
we have here is a post request, and action is empty, data is automatically submitted to the current path, i.e. the view function login, we separately for different requests

 

request method acquaintance
            request.method   acquiring all upper distal string request type (the GET / the POST)
            `` request.GET``      obtain all the data carried by the get request, similar to a large dictionary, is a listing
             request.POST     acquisition request carrying post All data is similar to a large dictionary, is a list of 
                values is divided into two request.POST.get ( 'hobby')   a default list of the last element taken
                     request.POST.getlist ( 'hobby')   directly to the list intact Fixed withdrawn
                    

 

 

 

3. pycharm database connection 

The front end of the data reception is completed, the next step is to obtain data for comparison database, the database is first connected

Sidebar database you want to connect to the database pycharm operation acts as a database of clients

      

           

 

 

 4.django connect to the database (******)

# Django default using built-in sqlite database, which is not very accurate on the date 
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}       
第一点: 如果你想让它其他的数据库  需要修改settings配置文件中配置
1. settings文件中配置
        DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'day38',
        'HOST':'127.0.0.1',
        'PORT':3306,
        'USER':'root',
        'PASSWORD':'123',
        'CHARSET':'utf8'
    }
}

 

第二点:如果此时启动项目会报错,说你没有导入mysqldb模块,这个模块已经不使用了,我们直接导入pymysql

 

2.还要在项目名下的init文件或者是应用名下的init文件中告诉django不要使用默认的mysqldb连接mysql,而是使用pymysql
    import pymysql
    pymysql.install_as_MySQLdb()

5.django orm 简介(数据库迁移)

强调:django orm不会帮你创建库,需要你自己手动创建库,它只能帮你创建表(建议你一个django就新建一个数据库)

1.首先需要在应用下的models.py中书写模型类
        class User(models.Model):
            # django会默认给你的表创建一个名为id的主键字段
            # id = models.AutoField(primary_key=True)  # 一旦你自己指定了主键字段 那么django就不会自动再帮你创建了
            username = models.CharField(max_length=32)  # username varchar(32)   CharField必须要指定max_length参数
            password = models.IntegerField()  # password int

2. 需要执行数据库迁移(同步)命令才能修改数据库(******) python3 manage.py makemigrations # 仅仅是在小本本上(migrations文件夹)记录数据库的修改 并不会直接操作数据 python3 manage.py migrate # 将数据库修改记录 真正同步到数据库 注意:只要动了models中跟数据库相关的代码 就必须重新执行上面的两条命令 缺一不可(******)
  

当你熟练掌握之后 你可以采用简写的方式
  tools
    run manage.py task

 

         

 三、表单操作

1.表字段增删改查

表字段的增删改查
        增
            当一张表已经创建出来之后 后续还想添加字段,可以有两种方式
                1.给新增的字段设置默认值
                    addr = models.CharField(max_length=32,default='China')  # default该字段默认值

                2.给新增的字段设置成可以为空
                        age = models.IntegerField(null=True)  # 该字段允许为空
                 
        删 (慎用)
            删除字段 直接在models.py中注释该字段 然后重新执行两条迁移(同步)命令即可
            注意:执行完之后 表中该字段所对应的所有的数据全部删除
                 一般情况下 基本是不会用到真正意义上的删除

 

 

 

 

 

 

 2.表记录的增删改查

#查询

表记录的增删改查
    操作django orm都是以模型类名作为开头
    先导入 from app01 import models
    
    以用户的增删改查为例
                
先连接数据库展示所有用户信息
    1.获取模型表中所有的数据
        models.User.objects.all()  # 结果也是querySet对象    只要是queryset对象 就可以点query查看内部sql语句
    2.筛选相应的数据
        1.直接获取对象的
            models.User.objects.get(**kwargs)  # 条件不存在  立刻报错  不推荐使用
        2.获取querySet对象的(
                       1.querySet对象你可以把它看成是一个列表 里面放的是一个个的数据对象
                       2.querySet对象支持索引取值和切片操作 但是不支持负数 也不推荐你使用索引取值
                       建议你使用封装好的方法
            )
            queryset = models.User.objects.filter(**kwargs)  # 括号内多个参数是and的关系
            user_obj = querySet.first()  # 没有也不会报错  直接返回None

# queryset 对象

"""
1.res = models.User.objects.filter(username=username,password=password)
 filter查询出来的结果是一个"列表 列表内放的才是一个个的数据对象本身"
 当查询条件不存在的时候 不会报错 只会返回一个空列表
 filter括号内 支持写多个参数  并且参数与参数之间是and的关系

2.querySet对象 支持正数索引取值支持切片,但是不推荐索引取值,一旦为空索引取值会报错(切出来的结果还是一个querySet对象)
 (如你通过名字查找有三个同名的列表里面会有三个对象,可以索引取值也可以切片取前两个对象),如:res[0:2]

3. user_obj = models.User.objects.filter(username=username).first()  # 拿列表中第一个数据对象
  用first虽然内部源码也是按照索引取值返回出来,但是没有数据时也不会报错,只会返回None

4.print(res.query)  # 只有querySet对象才可以直接点query查看年内部对应的sql语句,
    filter拿到的结果就是一个querySet对象(你现在只需要知道filter拿到的结果就能够点query查看sql语句)
    如:print(res.query)
                 SELECT `app01_user`.`id`, `app01_user`.`username`, `app01_user`.`password` 
                 FROM `app01_user` 
                 WHERE (`app01_user`.`username` = jason AND `app01_user`.`password` = 123)
"""

#登录—— 获取数据库数据进行比对

user_obj = models.User.objects.filter(username=username).first()  # 拿列表中第一个数据对象
if user_obj:
    if user_obj.password == password:
        return redirect('http://www.xiaohuar.com') #登陆成功重定向到网站

return HttpResponse('用户不存在 ')

#增

1.create()方法
    res = models.User.objects.create(username=username,password=password)  # insert into user(username,password) values(username,password)
    # create方法能够新增数据 并且有一个返回值,返回值就是新增的数据对象本身
        # print(res.username)
        # print(res.password)
2.利用对象的绑定方法
    user_obj = models.User(username=username,password=password)
    user_obj.save()    

#注册功能

(先写urls路由与函数对应关系,再写注册html页面,再写注册函数新增用户)

#删和改

3.修改用户
    1.利用queryset对象的update批量修改的方法
        models.User.objects.filter(age = 18).update(**kwargs)  # 会将queryset中所有的数据全部修改
    
    2.利用对象修改属性的方法
        user_obj = models.User.objects.filter(**kwargs).first()
        user_obj.username = 'jason'
        user_obj.save()  # 该方法 会将数据库中所有的字段全部重写修改一遍 效率极低 不推荐使用

4.删除用户(不会真正删除数据  通常都是给数据加一个表示是否删除的字段)
    1.利用queryset对象delete批量删除
        models.User.objects.filter(age = 18).delete()  # 会将queryset中所有的数据全部删除

#修改功能

 

 

 

 

 

 #删除功能

 

 

 

Guess you like

Origin www.cnblogs.com/xp1315458571/p/11531057.html