Django static resource request, the connection and operation of the database

White will than three tricks (Yaojin)

from django.shortcuts import render,HttpResponse,redirect

Is three or more, in this way need to import.

usage:

一、HttpResponse

def login(request):
   return HttpResponse('hi , you')

This is the return of the string, for example, you write a page suffix is ​​login, and is already bound in urls inside, we will call this function, and then return the string returned will be displayed on the page.

Two, render

def reg(request):
    user_dic = {'a.txt':1, 'b':2}
    return render(request,'reg.html', locals())

This is a return to a html page, and the third parameter could have been written by a dictionary { "xxx": user_dict},

But if when you want to pass a lot of dictionary, it will become very complicated, this time into locals (), which is the name of the current space of all variable names passed all reg.html.

three,

def home(request):

    return redirect('https://www.baidu.com')

This is a redirection, an analogy, you redirect is not logged in, go directly to some of the pages, he will jump to the login page, which is redirected. The above chestnuts is redirected to Baidu.

Static configuration file

Static files, such as the use of the site:
its own written js
own written css
third frame bootstrap fontwesome sweetalert

Static file resource site used static files are placed unified normally folder

In the settings of STATIC_URL = '/ static /' is a static resource access interface prefix
"" "If you want to access static resources you must start with a static" ""

For example, you want to access my own pages in the static resource, it is necessary so to request less.

127.0.0.1:8001/static/"你要访问的静态资源文件名"

Manually configure a static file access resources

STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'static'),
    os.path.join(BASE_DIR,'static1'),
    # os.path.join(BASE_DIR,'static2'),
]

Static resource files you create folders, be sure to configure the settings up inside.

This time the boss there is too much to ask, says he wants to change the prefix access interface static resources, if your html pages, called these static resources, such as bootstrap, css, all this time you want to change, the quantities will be very large, so use way to write, that is,

Dynamic analysis interfaces prefix

{% load static %}
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>

This way, then, will change as you access the interface prefix static resources and dynamic resolution, follow the change, do not worry, though life may not have such unreasonable demands of business, but writing either to prepare from time to time need.

Form of request form

We know that the way the default form request form submitted toward the rear end is get request.

Forms and form parameters can be written in the form of action
1. Do not write default towards current address submitted
2. Write only the suffix / index /
3. Write the full path

get and post requests distinction

When we get the request carries parameters, these parameters will be followed url. So it is very unsafe.

This time it should use post requests. And he was carrying size parameters is limited, only 1kb.

In the early days, if you want to post to submit a request to go to settings inside it a middleware commented.

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',
    ]

Otherwise requested page will fail.

requests Subjects and Methods

Our request is successful, the parameters are passed over, this time to get the data in the back-end (because your action is written, "")

So this time you have to accept a requests, it will receive a lot of things, which you heard arguments in the front POST inside, you can request.POST to get. If your request is to get in the way, then, is request.GET .

get and post acquire user data in the back end when the law is the same

 get和post在后端获取用户数据的时候 规律是一样的
    <QueryDict: {'username': ['admin', 'tank'], 'password': ['123']}>
    tank <class 'str'>
    123 <class 'str'>
    request.POST.get('username') 默认只取列列表的最后一个元素
    如果你想将列表完整的取出 你必须用getlist()

django database connection

 django连接MySQL
        第一步配置文件中配置
            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()

django orm Profile

Object-relational mapping orm

类                   数据库的表

对象                  表的记录

对象获取属性          记录的某个字段对应的值

优点:能够让一个不会数据库操作的人 也能够简单快捷去使用数据库

缺点:由于封装程度太高 可能会导致程序的执行效率偏低
有时候 结合项目需求 可能需要你手写sql语句

Note: Django's orm will not help you create the database, libraries need to create your own hands, will help you automatically create a table, you only need to write the code in line with django orm syntax can be.

Create a table

Write class app in the following 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必须要指定max_length参数
    username = models.CharField(max_length=64)  # 在django orm中 没有char字段  但是django 暴露给用户 可以自定义char字段
    # 设置password字段  password int
    password = models.IntegerField()

Note: You can not write that is the id field, and did not put it as the primary key, this error.

Written after class, to enter two commands in the command window.

Database migration command: Python manage.py makemigrations

This command does not create a table just to generate a record of your current operations recorded a small notebook (migrations folder)

Execution: Python manage.py the migrate

The real migration orm your statement to the (synchronized) to the database

No matter what you do to modify the database associated with operating in this models.py file, there are two re-run the above command! ! !

Additions and deletions to change search data (check only temporarily and increase)

check:

 res = models.Userinfo.objects.filter(username=username)

Check out a list, so you want to take the first, but does not recommend the use of res [0] to take, to use the first method django provided ()

user_obj = res.first()

Even if this is the first use of the underlying [0] to achieve, very dog ​​he is so written, does not allow users to write with it.

increase:

user_obj=models.Userinfo.objects.create(username=username,password=password)

Note to self: for example login page, after you run from the server, access the login page, will go again and this time the login page good binding function, that is, inside and urls / login bound of views in the function . Then when you submit data, this method will once again walk again, this time inside the method of return rende () and went to it again.

Guess you like

Origin www.cnblogs.com/chanyuli/p/11716846.html