Django overall architecture

Django overall architecture

  • All users can access resources to advance exposure programmers are good, if not expose the user can not access forever
  • All users can access resources to advance exposure programmers are good, if not expose the user can not access forever

A response to a request of three ways

First import module:from django.shortcuts import render,HttpResponse,redirect

1.1 HttpResponse

HttpResponse ( "response page content")

# 1. 首先在urls.py配置请求路径
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^httpresponse/', views.httpresponse),
]

# 2. 编写对应函数
def httpresponse(request):
    return HttpResponse("我是HttpResponse")

# 3. 浏览器中请求
http://127.0.0.1:8000/httpresponse

I HttpResponse

1.2 render

render: return html form content

1. Return html content
# 1. 首先在urls.py配置请求路径
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^httpresponse/', views.httpresponse),
    url(r'^renders/', views.renders),
]


# 2. 编写对应函数
def renders(request):
    return render(request, "02render.html")

# 3. 浏览器中请求
http://127.0.0.1:8000/renders

I render

2. Get back data dictionary in html by **
<!--02render.html-->
<!DOCTYPE html>

<body>
<h1>我是render</h1>
{{ user }}
</body>
</html>
# 1. 首先在urls.py配置请求路径
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^httpresponse/', views.httpresponse),
    url(r'^renders/', views.renders),
]


# 2. 编写对应函数
def renders(request):
    user_info = {"user": "randy", 'age': 18}
    # 注意:只能返回的是字典数据类型,其他数据类型则会报错
    return render(request, "02render.html", {'user': user_info})
# 3. 浏览器中请求
http://127.0.0.1:8000/renders

I render

{"user": "randy", 'age': 18}

3. locals get all the local variables **
<!--02render.html-->
<body>
{{ user_info }}<br>
locals可以获取当前所有局部变量:{{ num }} <br>
locals可以获取当前所有局部变量:{{ count }} <br>
</body>
</html>
# 1. 首先在urls.py配置请求路径
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^httpresponse/', views.httpresponse),
    url(r'^renders/', views.renders),
]

# 2. 编写对应函数
def renders(request):
    user_info = {"user": "randy", 'age': 18}   
    num=123
    count = 890
    # locals返回全部局部变量
    return render(request, "02render.html", locals())
# 3. 浏览器中请求
http://127.0.0.1:8000/renders

{ 'User': 'Randy', 'Age':} 18 is
about locals can obtain all current local variables: 123
about locals can obtain all current local variables: 890

4. Comparison of the background data acquired in two ways
  • By transmitting data of a dictionary, a plurality of data transmission is difficult when the preparation, with respect to the high efficiency of these locals
  • All transmitted to the front locals will namespace for all variables page, the relative efficiency of the end of the dictionary

1.3. redirect

redirect: Redirect to another page

# 1. 首先在urls.py配置请求路径
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^httpresponse/', views.httpresponse),
    url(r'^renders/', views.renders),
    url(r'^redirects/', views.redirects),
]

# 2. 编写对应函数

def redirects(request):
    print(request)
    # return redirect('/index') # 重定向指定的路径
    return redirect("https://www.baidu.com") # 重定向到指定的url
# 3. 浏览器中请求
http://127.0.0.1:8000/redirects  # 进入百度页面
  • Three are required to return, return all objects httpresponse
  • rendirect with data redirection
  • render without data

Second, the static configuration file

References css, js, third-party frameworks, the need for a static configuration file, otherwise the page will not be rendered,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--static不是文件,是静态资源访问的接口-->
    <script src="/static/bootstrap/js/jquery.js"></script>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
    <script src="/static/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h1>static</h1>
</body>
</html>

Static resource files usually used website unity are placed under static folder, and you need to configure a static resource files accessed manually setttings.py as follows

STATIC_URL = '/static/'  # 是访问静态资源的接口前缀
"""只要你想访问静态资源 你就必须以static开头"""

# settings.py配置,名字不可以更改
 STATICFILES_DIRS = [
        # 添加静态文件可以添加多个,拼接文件夹的路径
        os.path.join(BASE_DIR,'static'),
        os.path.join(BASE_DIR,'static1'),
        # os.path.join(BASE_DIR,'static2'),
    ]

note:

STATIC_URL = '/ static /' # prefix is ​​an interface to access static resource == static == is not the name of the folder you created, but a static resource access interface, the name can be changed, in order to avoid modifying the modified static in reference js, css can be set dynamically

接口前缀 动态解析静态文件
{% load static %}
<link rel="stylesheet" href="{% static '/bootstrap/css/bootstrap.css' %}">
<script src="{% static '/bootstrap/js/bootstrap.min.js' %}"></script>

Three, form form

default background items from a form submitted by default to get request, get request with parameters embodiment is carried back in the url url?username=admin&password=213213213213213, causing unsafe submit data, and it carries cedar limited size, the general post requests

# 采用post请求暂且要注释一个中间件
    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',
        ]

3.1 form form action parameter written form

  • Do not write the address of the current page default submission
  • Write only request address suffix (/ index)
  • Write full path

Subjects and Methods 3.2 request

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    {% load static %}
    <script src="{% static 'bootstrap/js/jquery.js' %}"></script>
    <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
    <script src="{% static 'bootstrap/js/bootstrap.js' %}"></script>
</head>
<body>
<form action="" method="post">
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-2 ">
                <h1 class="text-center">登录界面</h1>
                <input type="text" class="form-control" name="username"><br>
                <input type="password" class="form-control" name="password"><br>
                <input type="checkbox" name="hobby" value="backbll"> 篮球
                <input type="checkbox" name="hobby" value="xiaoball"> 小球
                <input type="checkbox" name="hobby" value="daball"> 打球<br>
                <input type="submit" class="btn btn-primary"><br>
            </div>
        </div>
    </div>
</form>
</body>
</html>
def login(request):
    # if request.method == 'GET':
    #     # 你应该针对不同的请求方式 有不同的处理逻辑
    #     # print('走了我')
    #     # 获取请求方式  结果是一个大写的字符串
    #     print(request.method,type(request.method))
    #     return render(request,'login.html')
    # elif request.method == 'POST':
    #     pass
    """由于get请求比较常见 并且业务逻辑简单 所以针对get不需要做逻辑判断 默认就是get请求"""
    if request.method == 'POST':
        # 获取前端传递过来的用户名和密码
        print(request.POST)  # post请求提交过来的数据  <QueryDict: {'username': ['admin'], 'password': ['123']}>
        # 你可以直接将request.POST当成字典即可
        username = request.POST.get('username')
        password = request.POST.get('password')
        hobby = request.POST.getlist('hobby')
        print(username,type(username))
        print(password,type(password))
        print(hobby,type(hobby))
        """
        <QueryDict: {'username': ['admin', 'tank'], 'password': ['123']}>
        tank <class 'str'>
        123 <class 'str'>
        request.POST.get('username') 默认只取列列表的最后一个元素
        如果你想将列表完整的取出 你必须用getlist()
        """
    # print(request.GET)
    # username = request.GET.get('username')
    # password = request.GET.get('password')
    # hobby = request.GET.getlist('hobby')
    # print(username, type(username))
    # print(password, type(password))
    # print(hobby, type(hobby))

    return render(request, 'login.html')
  1. Way acquisition request

    The request for access to different ways for different logical out, the default is a GET request ·

request.method  # GET / POST,<class 'str'>
  1. Submission of data acquisition front-end

    request.POST.get ( "") If more than one list of data such as hobbies, will finally get a hobby, so he can only get a value,

    request.POST.getlist ( "") may acquire a plurality of values, returns a list

    post requests submitted form data <QueryDict: { 'username': [ 'admin'], 'password': [ '123']}>

username = request.POST.get("username")
password = request.POST.get("password")

Four, django database connection

  1. pycharm database connection

pycharm connect to database database may cause not connected, because the resulting jdbc version, you can change the drive version, the award-winning database system that is more time SYSTEM +8:00

  1. django database connection

    • The first step in the configuration database connection in settings.py
    • The second step to change the way the database connection in --init--.py
    # 第一步配置文件中配置
    DATABASES = {
          'default': {
           'ENGINE': 'django.db.backends.mysql',  # 指定数据库 MySQL postgreSQL
            'NAME': 'day56',  # 到底使用哪个库
            'USER':'root',
            'PASSWORD':'root',
            'HOST':'127.0.0.1', 
            'PORT':3306,
            'CHARSET':'utf8'
       }
    }
    
    # 第二步 django默认使用的是mysqldb连接数据库  但是该模块不支持了 所以你要告诉django不要用mysqldb该用pymysql连接 你可以在项目名下面的__init__.py也可以在应用名下面的__init__.py文件中指定
    import pymysql
    pymysql.install_as_MySQLdb()
    1. django orm of operation

      Object-relational mapping orm

    class Database table
    Objects Record Form
    Object get property A field value corresponding to the recording

    Advantages: will not be able to make a database of people who can operate fast and easy to use database

    Cons: Because of the extent of the package is too high may lead to low performance of programs, sometimes in conjunction with project requirements may require you to hand sql statement

    Note: django orm of not automatically help you create a library, the library requires you to manually create the table will automatically help you create you just need to write code to comply with django orm grammar, models.py located next to write applications class

    1. Create a table
    # models.py
    class UserInfo(models.Model):
        # 设置id字段为userinfo表的主键  id int primary key auto_increment
        id = models.AutoField(primary_key=True)  # 在django中 你可以不指定主键字段 django orm会自动给你当前表新建一个名为id的主键字段
        # 设置username字段  username varchar(64)  CharField必须要指i定max_length参数
        username = models.CharField(max_length=32)  # 在django orm中 没有char字段  但是django 暴露给用户 可以自定义char字段
        # 设置password字段  password int
        password = models.IntegerField()
        # phone = models.BigIntegerField(default=110)  # 新增的字段 可以提前设置默认值
        # addr = models.CharField(max_length=64,null=True)  # 新增的字段 可以设置为空
    
    • The new field, set the default value or specified as null

    Create a table requires two commands:

    python manage.py makemigrations  # 初始化表,会在migrations文件夹中创建0001——initila.py,创建一条记录
    python manage.py migrate

    Step 1: Create models.py in the corresponding table in the class (if not specified id, he will automatically create a primary key id, and only for the primary key id,)

    Step Two: The command to use python manage.py makemigrations will produce migrations folder 0001__initial.py file, and it will produce a record in the database does not create a real database,

    The third step: Use python manage.py migrate to execute the command will create a real user information table, first created, Django will create additional databases

    Note: Once you modify the code in the database associated with models.py you have to restart the implementation of the above two commands

    • If you want to modify the field, you can be modified to create a class carefully re among the above two commands
    1. Additions and deletions to change search database

      Query data
      get (), filter (), all ()

    # 查询数据
    
    def login(request):
        if request.method == 'POST':
            username = request.POST.get("username")
            password = request.POST.get("password")
    
            # 1.get()  当查询条件不存在的时候 会直接报错   如果存在会直接给你返回 数据对象本身        不推荐使用
            # res = models.Userinfo.objects.get(username=username)  # select id,username,password from userinfo where username='jason'
            # print(res)
            # print(res.username)
            # print(res.password)
            # 2.filter()   当查询条件不存在的时候  不会报错而是返回一个空
            # 当条件存在的情况下 无论数据有几条返回的都是列表套对象的数据格式
            # filter可以当多个查询条件 并且是and关系
            res = models.Userinfo.objects.filter(username=username)  # select * from userinfo where username='jason' and password=123;
            # user_obj = res[0]
            # user_obj = res[0:3]
            # user_obj = res[-1]  # 你可以将filter查询出来的结果当做列表去对待 支持正数的索引取值和切片 不支持负数
            user_obj = res.first()  # 取queryset第一个元素
         print(user_obj)
     return render(request,'login.html')

    get usage:

  • When the query condition does not exist when a direct presence will give you an error if the returned data object itself directly (not recommended),
    • Multiple query conditions and relations
  • Direct return the object itself

    filter:

    • When the query condition does not exist when the error but not an empty
    • In the case where the presence of data regardless of the data format of the list is returned several sets of objects
    • filter can be a multiple query conditions and the relationship is and
    • Query results as a list, not recommended slice acquisition, support and value all sections of positive numbers, negative numbers are not supported
    • Returns a list of objects

    Note: Use the query conditions get, the data will not find an error, try to use the filter query data

    Creating a Data

# 插入数据
def reg(request):
    if request.method == 'POST':
        username = request.POST.get("username")
        password = request.POST.get("password")
        # 直接将用户名和密码写入数据库
        user_obj = models.Userinfo.objects.create(username=username,password=password)
        # insert into userinfo(username,password) values('admin','666');
        # create方法会有一个返回值  返回值就是当前被创建的数据对象
        print(user_obj)
    return render(request,'register.html')
# 修改数据
def update(request):
    user_id = request.GET.get("id")
    print(user_id)
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        models.UserInfo.objects.filter(pk=int(user_id)).update(username=username, password=password) # 会修改查询到的数据全被修改
        return redirect('/index')

    user_dic = models.UserInfo.objects.filter(pk=int(user_id)).first()

    return render(request, 'update.html', locals())

"""
    1.方式1
        modeles.Userinfo.objects.filter(**kwargs).update()  # 批量更新
        2.方式2  (不推荐使用 效率极低 会将每一个字段对应的值全部重写一遍)
        edit_obj = models.Userinfo.objects.filter(pk=edit_id).first()  # pk会自动帮你查找当前表的主键字段
        edit_obj.username = username
        edit_obj.password = password
        edit_obj.save()  
        
"""
# 删除数据

def delete(request):
    user_id = request.GET.get("id")

    models.UserInfo.objects.filter(pk=int(user_id)).delete()

    # rendirect重定向带数据
    # render不带数据
    return redirect('/index')
"""
 
        删除
        models.Userinfo.objects.filter(pk=delete_id).delete()
        """说真正的数据是不会被删除的 通常都是给数据设置一个是否删除的标志位"""

"""

A large table into two tables-one

Guess you like

Origin www.cnblogs.com/randysun/p/11746801.html