Two, Django installation and simple operation

A, MVC framework and MTV

  • MVC
    -called MVC, the Web application is divided into model (M), controller (C) and view (V) three, in a plug-in, loose coupling connected between them, responsible for the business object model associated with the database, view is responsible for interaction with the user (page), the controller accepts user input to complete the call to model and view the user's request (that is, url distribution)

  • MTV
    Django model is MTV
    • M represents the model (Model): responsible for the business object-relational mapping and database (ORM).
    • T represents the template (Template): responsible for how to display a page to the user (html).
    • V represents the view (View): is responsible for the business logic, and calls the Model and Template at the appropriate time.
    • In addition to the above three, you also need a URL dispatcher, it is the role of a URL of a page request distributed to the different treatment of View, View and then call the appropriate Model and Template

Second, download and install django

Official website address: https://www.djangoproject.com/download/

The current version is 1.11 version, and so in 2020 to learn a version 2.2

  1. Create a Django project started cmd terminal

  2. 下载Django:
    pip3 install django==1.11.9
  3. Create a Project Django
    Django-ADMIN startproject mysite to create a Django project called "mysite" is:

    Because pip.exe executed, so Django will be installed in the file where the pip;

    When they find scripts folder there Django, the installation is successful, it did not have to configure the environment;

    After installation is complete, to create a django project, if the following occurs, indicating that environment variable is not configured, Django the path you want to install the configuration environment variable

  4. Project files created introduce
    Once created, the directory will generate mysite project directory as follows:

    • manage.py ----- Django project inside the tool that can be called django shell and databases, project start close interaction with the projects, whether you will divide the framework of several documents, there must be a boot file, in fact, their own It is a file.
    • settings.py ---- contains the default settings of the project, including database information, debugging flags and variables other work.
    • urls.py ----- responsible for URL patterns mapped to the application.
    • wsgi.py ---- runserver command module on the use of wsgiref do a simple web server, see later renserver command, all content related to the socket in this file inside, and now do not need to pay attention to it.
  5. Run the project
    Python manage.py the runserver 127.0.0.1:8080
    # django now ready to start the project, but did not do what logic
    by instruction execution of the project, they can not write ip address, port,
    if you do not write, the default is 127.0 .0.1
    python manage.py runserver 8080
    if not even write port, the default is port 8000
    python manage.py runserver

    停止项目:ctrl+c

    When the above effect appears, indicating the success of the project has already started, you can access the web via input 127.0.0.1:8080, the effect is as follows:

  6. Create an application under mysite
    will find that there is no file view view the above functions, and so on, these files can be understood as the application, a project can have multiple applications, such as micro-channel, there is a payment application, a chat application, an applet, circle of friends, etc. etc ... each application should have its own logic, a need to create their own separate application
    Python manage.py startapp app01
    # manage.py file is created by executing the application note: It should be located in the file directory manage.py under the implementation of this sentence, because there is no other directory this file
    cmd command after execution, in addition to some manage.py before and mysite folder, and new life into a new folder app01, the folder contents as follows:

  7. pycharm create a startup Django project

Create a Django project, rarely use the command line, you can create with pycharm

  1. Under option in the File New Project

  2. Django configuration options

  3. Create, open in a new window

  4. The resulting file directory as follows:

    One of the templates is pycharm help us directly create good, put some template, which is the html file.
  5. Run the project:

    After clicking Run, the following occurs, it is to start the project a success

    In this case, the page input 127.0.0.1:8000, you can visit

    This is because we have not written any logic, then we do a simple login function

  6. Based on a simple example to achieve Django

We do a login page of the web project, the browser will be able to enter a URL to get the login web page

  1. Find someone urls.py
    from django.conf.urls Import url
    from ADMIN django.contrib Import
    from file function of view of introduction of import views # app01

    urlpatterns = [
        # url(r'^admin/', admin.site.urls),
        url(r'^index/', views.index),  # 模仿写出路由的配置
        # 配置路径,r'^/index/',这个前置导航斜杠不需要添加.
        # 正则,可以让路径不用写死,index/dsad/qweq/fdsf/...也能匹配到
    ]
  2. Write view function views
    from the render django.shortcuts Import

    # Create your views here.
    
    def index(request):# request是一个形参,接受所有请求的内容
        return render(request,'login.html')
    The reason behind render html files can be written directly:
    why can write login.html directly, because settings.py configuration file has been configured path, you can directly get
    • There's configuration file in settings.py
      • TEMPLATES there is a 'DIRS': [os.path.join (BASE_DIR, 'templates')]
      • BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))
    • ABSPATH ( File ) This is a settings file
    • os.path.dirname (os.path.abspath ( File )) is the parent directory folder settings third_pro
    • os.path.dirname (os.path.dirname (os.path.abspath ( File ))) is the entire file of the project folder third_pro
    • So BASE_DIR is the file folder of this project, which is the outermost layer of the file folder third_pro
    • 'DIRS': [os.path.join (BASE_DIR, 'templates')] is spliced ​​path can be found inside the html document templates directly
  3. Write template templates, create html file here

    <h1>欢迎来到登录页面</h1>
    
    <form action="">
        用户名:<input type="text" name="username">
        密  码:<input type="text" name="password">
        <input type="submit">
    </form>
    Note: name attribute must have, because when price data through the form, you can put a value entered by the user with the past
  4. This simple to complete a web project
    by entering 127.0.0.1:8000/index, we will be able to get the written page

  5. Log function to achieve perfect Django

Users enter a user name password, enter the background to determine whether the correct user name and password

First, distinguish between get and post request request

  • Default get request form form
    data submitted by the user or returned to the index that path
    request.GET - GET request all data transmitted, queryDict type

    <input name='username'>
      request.GET.get('username')
        # 获取 name='username' 的 input 标签用户输入的内容
  • post request
    request.POST - all data transmitted to the POST request, queryDict type

    <input name='username'>
      request.POST.get('username')
        # 获取 name='username' 的 input 标签用户输入的内容

Because you want to get the data submitted by the user, the form is submitted in two ways:

  1. get the requested data:

    from django.shortcuts import render,HttpResponse

    def index(request):
    print(request.GET) #<QueryDict: {'username': ['dazhuang'], 'password': ['123']}>
    username = request.GET.get('username')
    password = request.GET.get('password')
    print(username,password)
    if username == 'dazhuang' and password == '123':
    return HttpResponse('登录成功!') --- 回复字符串数据
    else:
    return HttpResponse('失败!')
    return render(request, 'login.html')

There is a problem: when the page is requested directly by the path, is get request, submit the form data form also get requests will not tell, so get with the requested page request, submit data request form with the post form

  1. post request data:

views view function to write the file:

def index(request):
    print(request.method) #'POST' 'GET'
    if request.method == 'GET':
        return render(request,'login.html')

    else:
        # print(request.GET)
        print(request.POST)
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'dazhuang' and password == '123':
            return HttpResponse('登录成功!')
        else:
            return HttpResponse('登录失败!')

html file:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>

</head>
<body>
<h1>欢迎来到登录页面</h1>

<form action="/index/" method="post">  # 给一个method属性规定post请求
    用户名:<input type="text" name="username">
    密  码:<input type="text" name="password">
    <input type="submit">
</form>

</body>
</html

settings file:

Turn off a post authentication mechanism when a data request is submitted, settings profile

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

final effect:

输入正确的用户名、密码:dazhuang、123,提交,

Login successful, no login failure

Some points to note:

  • Problems which need to pay attention urls.py
    url (r '^ index /' , views.index), the first parameter: path regular second argument string: corresponding to the view function
  • the views.py
    DEF Login (Request):
    acquisition request Method: request.method - 'the GET', 'the POST'
    `` request.GET`` - the GET request is transmitted to all data, queryDict type
    request.POST - POST request transmitted All data, queryDict type

    request.POST.get ( 'username')
    request.GET.get ( 'username')
    return the HttpResponse ( 'string') --- reply string data
    retuen render (request, 'login.html' )

Third, a brief summary

  1. django download and install

    Download: pip install django == 1.11.9

    Create a project
    Django-ADMIN startproject Qingqing
    cd Qingqing
    startup items: Python manage.py the runserver 127.0.0.1:8001
    cd Qingqing
    create app: python manage.py startapp xiaoqing

    You need to add a profile configured in a project settings.py the app
    INSTALLED_APPS = [
    'Xiaoqing', app name
    ]

    = The INSTALLED_APPS [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles' ,
    # can be written in two
    'app01.apps.App01Config',
    # 'app01',
    ]

  2. Two frame mode

    The MVC
    M: Models database-related
    V: views view logic associated
    C: url different distribution path controller controllers find different views of a function of
    the MTV
    M: Models database-related
    T: templates template, HTML files,
    V: views view logic associated
    + url controller different paths to find a different view functions
    MVVM

Guess you like

Origin www.cnblogs.com/yangzm/p/11209808.html