Django file configuration, request object, connection to MySQL, ORM

Article directory

  • Django static files and related configurations
    • Static file preface
    • Static file related configuration
  • form form
  • request object
    • request request result
    • GET request
    • POST request
  • pycharm connects to database
  • Django connects to MySQL
  • Introduction to Django ORM

Django static files and related configuration

In this blog I will introduce relevant knowledge through a user login page

First we write an html page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../js/jquery-3.7.1.min.js"></script>
    <script src="../bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../bootstrap-3.4.1-dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1 class="text-center">Login page</h1>
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <form action="" method="post">
                    <div class="form-group">
                        username: <input type="text" class="form-control" name="username">
                    </div>

                    <div class="form-group">
                        password: <input type="password" class="form-control" name="password">
                    </div>

                    <div class="form-group">
                        <input type="submit" class="btn btn-block btn-success" value="Login">
                    </div>

                </form>
            </div>
        </div>
    </div>
</body>
</html>

Static file preface

Files that change infrequently are mainly for various resources used by html files, such as css files, js files, img files, and third-party framework files

In Django, static file resources need to be stored in a separate directory. This directory is named static directory

 static directory Most of the types of files in this directory can be divided into more
├── css directory
├── bootstrap.min.css
└── js directory
├── jquery-3.7.1.min.js
└── bootstrap.min.js
└── img directory
├── utils directory/plugins directory/libs directory/others directory/do not create a directory

Resource Access

The reason why we can enter the route in the address bar to obtain the corresponding resource login resources is because the programmer has opened the corresponding resource interface in advance. If you enter http://127.0.0.1:8000/admin in the URL, you can access the corresponding resource interface. Corresponding interface resources. Otherwise, if the corresponding interface is not opened, it cannot be accessed.

Static file resource access
When css and js are directly introduced into django, dynamic effects cannot be used directly. Static file configuration must be added, and jquery must be added before adding Bootstrap. It is inaccessible by default because we have not set up an access interface for static file resources in advance. As shown below

The login request can be successful because the port http://127.0.0.1:8000/login/ has been opened on the backend, so the browser can access it after entering the corresponding link in the address bar; but the request URL: http: //127.0.0.1:8000/static/bootstrap-3.4.1-dist/css/bootstrap.min.css is because the backend does not open this port, so the browser cannot access resources when requesting resources from this URL.

So how to solve it?

In theory, we should fill in the corresponding relationships in URLs, but there are too many static files, so Django has opened a static file resource interface specifically for static files.

Static file related configuration

1. How to configure static file configuration?

First, find the last STATIC_URL = /static/’ in settings, and configure the paths of all static resources below this code.

2. Static file token

 STATIC_URL = './static/' # Token for accessing static file resources
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'), # The name of the directory where static file resources are stored
os.path.join(BASE_DIR, 'static1') # The name of the directory where static file resources are stored (you can also set the directory with another name)
]
\t\t
'When the token is correct, it will take the following paths and search from top to bottom in the list. Once found, it will return'

Search order: Static file token>>>>Interface resource file (top to bottom, end when found), only the correct token is qualified to access the interface file resource

What if we just want to switch the interface token?

At that time, we have to go to all places where tokens are used and modify them one by one. However, sometimes the browser will request temporary cache content to be sent to us. It is impossible for us to modify static one by one, which is too troublesome. , so we can directly dynamically parse

3. Dynamic parsing of static file tokens

 Static file matching
<link rel="stylesheet" href="/static/bootstrap-3.4.1-dist/css/bootstrap.min.css">
<script src="/static/bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>

If we want to change the token 2, we need to change the door-to-door static file configuration to the following template syntax (i.e. dynamic parsing)

 The template syntax provided by django {<!-- -->% load static %}, relative to the module
'In order to prevent tokens from switching all the time, set up a method that specifically listens for tokens. After setting up, there will be a dynamic parsing back-end setting and the front-end automatic parsing settings are the same'
{<!-- -->% load static %}
<link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
<script src="{% static 'bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>

After this modification, every time we want to change the token, we can directly change STATIC_URL='/static/' to the name we want in the settings, such as STATIC_URL= '/UpdateStatic/', Django will automatically parse it dynamically for us later, as shown below

form form

 action controls the address of data submission
1.action="" The data is submitted to the address of the current page by default.
2.action="http://www.baidu.com" Specifies to submit the complete URL
3.action="/login" Submit the login address of the current server

Supplementary request method

1. Get request: Request data from the server, and can also carry some additional requirements.
How to carry extra data: In the address bar, URL?xxx=yyy & amp;uuu=zzz, but the size of the data carried after the question mark is limited (2-8kb), and sensitive data (password) cannot be carried

2.Post request: Submit data to the server
Ways to carry additional data: request body. The data carried in the request body is highly secure and has no size limit.

To send a post request in the early stage, you need to comment out this line of code in the settings configuration file as follows:

get request and post request are as follows

Points to note about form forms

  1. About request method
  2. To obtain user tags, you must add the name attribute. If you do not add the name attribute, it will not be received by the backend.
  3. Modify the configuration in settings

request object

request result

Syntax Description
request.method Get the request method result is a pure uppercase string
request.POST Get the ordinary data sent by the POST request (excluding files)
request.POST.get() By default, only the last data value in the list is obtained
request.POST.getlist() Get the entire list corresponding to the key no matter how many data values there are
request.GET Get the non-sensitive data carried behind the url
request.GET.get() By default, only the last data value in the list is obtained
request.GET.getlist() Get the entire list corresponding to the key no matter how many data values there are

The Request function will be triggered through different request methods and needs to execute different business logic codes.

 def index(request):
return HTTpReponse('hello world!')

Function: After the browser accesses a certain URL, it finds a function in the corresponding view through routing, and then passes the browser’s request to this function. This is why a formal parameter is defined, and usually the formal parameter name is :request, this is a specification.

The request contains the request sent by the browser to the Django server. There are two common methods of sending requests: GET and POST.
The form in which they carry requests is different.

GET request

index.html file (provided that the basic environment of Django has been set up)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    {<!-- -->% load static %}
    <script src="{% static 'js/jquery-3.7.1.min.js' %}"></script>
    <script src="{% static 'bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
    <link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
</head>
<body>
    <div class="container">
        <h1 class="text-center">Login page</h1>
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <form action="" method="get">
                    <div class="form-group">
                        username: <input type="text" class="form-control" name="username">
                    </div>

                    <div class="form-group">
                        password: <input type="password" class="form-control" name="password">
                    </div>

                    <div class="form-group">
                        <input type="submit" class="btn btn-blcok btn-success">
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

Use the form form to submit the request using the get method. If the action is not filled in, it will be submitted to the current address by default.

The way to submit a request with the GET method: carry the request data in the URL, let’s check it through debug in Django. (You need to submit it first, keep the parameters of the URL, then enable debug, and then refresh the page, because debug will be blocked as soon as it is enabled)

The request contains the method for the browser to submit the request, and the corresponding request method contains the carried data. We can extract this data for processing. As can be seen from the picture above, these data are in the form of a dictionary, and the key of the dictionary is the value of the name attribute of the input box in the HTML file.

In view.py file

 from django.shortcuts import render,HttpResponse,redirect

def index(request):
# print(request.method, request) # View the request submission method
username = request.GET.get('username')
password = request.GET.get('password')
# Get the data carried by the request submitted by the get method, and obtain the value according to the dictionary form: the key value is the name attribute value
print(username,password)
\t
return render(request,'index.html')

Browser opening effect:

It is recommended to use .get(key) to obtain the value of dictionary key, so that if the key does not exist, a None will be returned, and [key]If the value is obtained, an error will be reported if the key does not exist.

However, it is usually unsafe to submit data using the GET method. Compared with the account and password login function, POST requests are used.

Note: request.GET obtains the content after the URL?

As long as there is no problem with the URL token accessed by the user, it can still be handed over to the corresponding view function for processing: such as

 http://127.0.0.1:8080/index/?username=jack & amp;password=000

This requires the user to enter this kind of URL. When submitted to the backend, only /index/ after the ip + port will be recognized, and ? The content following will be submitted to the backend as additional data. So this request will be handed over to the index view function. Then use request.GET to get that extra data. We will demonstrate together below the post request

POST request

First change the form submission request method to POST:

Open with browser:

It can be found that our HTML file cannot be displayed normally. After checking the error message, it is found that it is due to csrf. At present, we do not need to understand why this error is reported. The solution is, in the settings.py file:

At this point, if we restart Django and submit using the post method, this error message will not appear.

We use debug in views.py to look at the content of the POST request:

According to the picture above, we can find that request has two attributes that store the data submitted by the browser: POST and body. When submitting using the GET method, no value is found in the body attribute, so let’s print them one by one to see their differences.


The POST attribute can be understood as storing values in the form of a dictionary, while the body stores binary values. So for convenience, we still use POST to solve the problem.

Demonstration of using GET attributes with POST attributes:
Modify the URL and form submission method is post.

It can be found that the GET attribute only obtains the content after the URL, while POST obtains the data actually entered by the user.

get() and getlist()

There is a very strange phenomenon in Django. From the picture above, we can find that the key corresponds to a list. Our get() does not take out a list, but the values in the list. This is a value-retrieval method that comes with Django, rather than the get() method we usually see for obtaining dictionary values.

In fact, the get() here takes out the last value in the list. We will understand after modifying the HTML page and submitting it.

It can be found that there are now two inputs with the same name attribute value, so we can submit them again after inputting them.


As can be seen from the above figure, get() takes out the last value of the list, so getlist() is very clear and directly obtains the entire list.

Summary:

In some view functions, we will write two situations. The first is the operation we perform if the browser uses POST to transfer data, and the other is the operation we should perform if the browser uses GET request.

Usually the access page sends a GET request. If it is a login interface, the view function will be written like this:

 def login(request):
if request.method == 'POST':
Request information extraction process....
\t\t
if account password verification is successful:
Login status binding...
return redirect(redirect to home page)
else:
return Returns the account or password error result
\t\t\t
return render(request,'Login page.html')

pycharm connects to database

1. When pycharm connects to the database for the first time, you must download the corresponding driver. If the driver does not work, change the driver. To verify, use the login user name (port and address) and library name. To verify the login, use test connection

2. Log in with the administrator account and password, and connect to the database you need (the database must be created in advance). Before connecting, you can click Test Connection to test the connection once. Note: You cannot log in as an administrator in the company!


3. Successfully connected successfully

Django connects to MySQL

The sqlite3 that comes with django is a small database with relatively few functions and is mainly used for local testing. Actual projects will replace it

1. Modify the database setting in the configuration file to connect django to MySQL

The default in the django configuration file is sqlite3 database
DATABASES = {<!-- -->
    'default': {<!-- -->
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

================================================== ====

To connect django to MySQL, you need to modify the above configuration
1. Configure in the first configuration file
DATABASES = {<!-- -->
    'default': {<!-- -->
        # 'ENGINE': 'django.db.backends.sqlite3', # Modify to MySQL database
        # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # The connection database name must be created before you can specify it.
        'ENGINE': 'django.db.backends.mysql', # Modify to MySQL database
        'NAME': 'user', #Connection database name must be created before you can specify it
        'HOST': '127.0.0.1', # URL
        'PORT': 3306, # Port
        'USER': 'root', # Specify user
        #'PASSWORD': '123', because my mysql does not have a password set, I don’t need to fill it in.
        'CHARSET': 'utf8' #Character encoding
    }
}
 Note that the names on the left must be capitalized! ! ! !

In addition, there may be problems with the link. You need to specify the link MySQL module.
MAC Django2.2.2 version requires writing a line of code in __init__.py in the project or application directory
import pymysql pymysql.install_as_MySQLdb()
If there is an encoding problem, click the blue link and change decode to encode.
MAC does not need to install mysqlclient
\t\t\t\t
WIN Django2.2.2 version does not require writing a line of code in __init__.py in the project or application directory
WIN requires mysqlclient to be installed

2. Manually change the default mysqldb to pymysql

By default, Django uses the mysqldb module to link to MySQL, but the compatibility of this module is not good. You need to manually change it to pymysql to link, and you need to specify the module.

Django1.X version needs to write code in __init__.py in the project directory or app directory

 import pymysql
pymysql.install_as_MySQLdb()

Django2.X and above can be solved directly by downloading the mysqlclient module

 pip3.8 install mysqlclient

? ps: There is not much problem with downloading this module on windows. It is mainly because there may be problems with mac computers.

Introduction to Django ORM

ORM: Object, Relations, Mapping. Abbreviation: object-relational mapping

Advantages: When operating the database in Django, you do not need to write native SQL statements, but use object-oriented syntax and some methods to operate the database
Disadvantages: The degree of code encapsulation is too high, resulting in problems: execution efficiency is reduced, which can be ignored for now. You need to write native SQL statements yourself

Object-relational mapping operates the database in an object-oriented manner, which requires corresponding relational mapping. The data can be divided into libraries, tables, field information, and pieces of data, and object-oriented relationships need to be used to correspond. So there is the following corresponding relationship.

  • Database ======= Object-oriented model
  • Table ======= Class
  • Field ======= Class Attribute
  • Logging ======= for each instance
 What is ORM?
The Object Relational Mapping (ORM) mode is a technology that solves the mismatch between object-oriented and relational databases.
The ORM framework is a bridge connecting to the database. As long as it provides a mapping relationship between persistence classes and tables, the ORM framework can refer to the information in the mapping file at runtime to persist objects into the database.
\t
Why use ORM?
When we implement an application without ORM, we may write a lot of data access layer code to save, delete, and read object information from the database, and these codes are all repeated.
Using ORM will greatly reduce repetitive code. Object-relational mapping mainly implements the mapping of program objects to relational database data.
Classes are mapped to tables, objects are mapped to records, and object point attributes are mapped to values corresponding to fields.
\t\t
The existence of ORM allows python programmers who do not know MySQL to use python syntax to operate MySQL simply and quickly
\t
1. First go to the application directory and write the model class in models.py
class User(models.Model): # Similar to defining the table name
id = models.AutoField(primary_key=True) # Similar to creating a new record ID primary key
name = models.CharField(max_length=32) # Similar to defining a normal varchar field
pwd = models.Interfield() # Similar to the definition
\t\t
id int primary key auto_increment
namevarchar(32)
pwd int
\t\t
'''Note that multiple attributes can be added within the brackets'''
\t
2. Database migration and synchronization commands
2.1>Record database-related operations in models to the migrations folder
python38 manage.py makemigrations
\t\t
2.2>Use the operation commands to actually operate the database
python38 manage.py migrate
\t
When modifying the database-related code in models, you must execute the above two commands, otherwise they will be invalid.
ps: It can be abbreviated or you can specify the application to be migrated/synchronized separately Tools>Run Manage.py Task
\t
3. The primary key of the table is in ORM. You don’t need to write it. ORM will automatically add a primary key of ID for you.
If you need a name other than id for the primary key, you can only create it yourself.