Process Django (Django to build a virtual environment, as well as a brief project creation template, view, model)

Copyright: Changan white https://blog.csdn.net/weixin_44074810/article/details/90740360

A, Django introduction
MVT modes:
1. M is a spelling Model, the same function M in MVC, is responsible for interacting with the database, data processing.
2. V spelling of View, and C functions in the same MVC, receives the request, performs service processing and returns a response.
3. T spelling of Template, and V in MVC same function, responsible html package structure to be returned.

Django build a virtual environment in a virtual machine

  1. Installation command virtual environment:
sudo pip install virtualenv
sudo pip install virtualenvwrapper

2. Create a directory used to store the virtual environment

mkdir $HOME/.virtualenvs

3. Open ~ / .bashrc file and add the following:

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh
在第三步如果出错了可以
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
       -----> 添加上这句 

4, run

source ~/.bashrc
  1. In python3, create a virtual environment
mkvirtualenv -p python3 虚拟环境名称
例 :
mkvirtualenv -p python3 py3_django

Second, how to use a virtual environment?

7. 使用虚拟环境的命令 :workon
例 :使用py3_django的虚拟环境
workon py3_django

8. 退出虚拟环境的命令 :deactivate

3.删除虚拟环境的命令 :rmvirtualenv 虚拟环境名称
例 :删除虚拟环境py3_django
先退出:deactivate
再删除:rmvirtualenv py3_django

Installation Kit in a virtual environment

  1. Kit installation location:
    next python3 Version:

    ~/.virtualenvs/py3_flask/lib/python3.5/site-packages

  2. package installation django-1.11.11 version of the python3:
    PIP the install package Name
    Example: installation package django-1.11.11
    pip install django == 1.11.11

  3. View virtual environment installed packages:
    PIP List

Third, create a Django project
Step
1. Create a Django project
django-admin startproject name

  1. Create a sub-applications
    Python manager.py startapp name

  2. Create a Project
    1. Create a Project command:
    Django-ADMIN startproject Project Name
    Example: you want to create a project called bookmanager of code in the desktop directory, run the following command:
    cd ~ / Desktop / Code
    Django-ADMIN startproject bookmanager
    View directory tree diagram tree command can be used

    1. Directory project of the same name, here bookmanager.

    2. settings.py is the project's overall profile.

    3. urls.py is the project's URL configuration file.

    4. wsgi.py project WSGI-compatible Web server entry.

    5. manage.py is a project management file, through its management of the project.

    6. Run the development server
      running the server command as follows:
      Python manage.py the runserver ip: port
      or:
      Python manage.py the runserver
      can not write IP and port, the default IP is 127.0.0.1, the default port of 8000.

      1. django default modal work in Debug mode, if you add, modify, delete the file, the server will automatically restart.
      2. Press ctrl + c to stop the server.

2. Create a sub-applications
created using the command sub-applications:
Python manage.py startapp sub-application name

manage.py is automatically generated when the above-mentioned project management file is created.
Example: In the bookmanager project just created, you want to create a user-book application modules, perform:
1. cd ~ / Desktop / code / book
2. Python manage.py startapp book
sub-application directory structure Explanation:
1 . admin.py configuration file associated with the site management background site.
2. apps.py file for configuration information about the current sub-application.
3. migrations directory used to store the database migration history files.
4. models.py the user to save the file database model classes.
5. tests.py document for developing test cases, write unit tests.
6. views.py file for writing Web applications view.

  1. Registration install sub-applications
    in the project configuration file in settings.py, INSTALLED_APPS term preservation of the project has been registered sub-installed application,
    the initial project INSTALLED_APPS in:
    register a sub-installation method of application, the configuration file is sub-application apps .py in the Config class INSTALLED_APPS added to the list.
    Example: just created book sub-applications added to the project, can be added to the list in INSTALLED_APPS
    'book.apps.BookConfig'

  2. Set pycharm environmental
    issues 1: will be able to find jango module
    type in a terminal: which python can quickly find the path to set the module django

Fourth, the model
1. Django prompt database development:
1. MVT design pattern Model, dedicated to interact with the database corresponding to the (. Models.py )
2. Since the Model embedded in the ORM framework, there is no need for direct database programming.
3. instead model class definitions, additions and deletions is completed through database table change search model classes and objects.
4. frame is to the ORM rows database table associated with the respective object, each conversion. makes the operation of the object-oriented database .

Step 2. Django for database development:
1. Define model class
2. migration model
3. The operation of the database

  1. Definition Model
例:
    在models.py中定义模型类,继承自models.Model

    from django.db import models

    # Create your models here.
    # 准备书籍列表信息的模型类
    class BookInfo(models.Model):
        # 创建字段,字段类型...
        name = models.CharField(max_length=10)

    # 准备人物列表信息的模型类
    class PeopleInfo(models.Model):
        name = models.CharField(max_length=10)
        gender = models.BooleanField()
        # 外键约束:人物属于哪本书
        book = models.ForeignKey(BookInfo)

2. The model migration (to build the table)

是在pycharm中最下面的 Terminal 中进行输入
迁移由两步完成 :
      1. 生成迁移文件:根据模型类生成创建表的语句
           python manage.py makemigrations
      2.执行迁移:根据第一步生成的语句在数据库中创建表
           python manage.py migrate

V. site management

1. 站点: 分为内容发布和公共访问两部分
2. 内容发布的部分由网站的管理员负责查看、添加、修改、删除数据
3.Django能够根据定义的模型类自动地生成管理模块
4. 使用Django的管理模块, 需要按照如下步骤操作 :
    1.管理界面本地化
    2.创建管理员
    3.注册模型类
    4.发布内容到数据库

1. The local management interface
in the settings.py Lane
LANGUAGE_CODE = 'EN-US' ----> 'Hans-ZH'
TIME_ZONE = 'UTC' ----> 'Asia / of Shanghai'
to set the time of the language and
the local of language is to be displayed and time using the local habits, localization here is carried out in China.
Chinese mainland Simplified Chinese, time zone, use the time zone Asia / Shanghai, pay attention here when not in use District, Beijing.

2. Create an administrator

创建管理员的命令 :
   python manage.py createsuperuser
按提示输入用户名、邮箱、密码
重置密码
   python manager.py changepassword 用户名

登陆站点可以输入 python manage.py runserver 点击IP连接输入用户名和密码登陆

3. The model class register
in the register file of the application admin.py model class
needs to import model module: from book.models import BookInfo, PeopleInfo

4. Publish content to the database
after the release of content, optimization model class show

# 准备书籍列表信息的模型类
class BookInfo(models.Model):
    # 创建字段,字段类型...
    name = models.CharField(max_length=10)
添加下面的代码:设置一个str方法
    def __str__(self):
        """将模型类以字符串的方式输出"""
        return self.name

Sixth, views, and URL

1. 站点管理页面做好了, 接下来就要做公共访问的页面了.
2. 对于Django的设计框架MVT.
    1. 用户在URL中请求的是视图.
    2. 视图接收请求后进行处理.
    3. 并将处理的结果返回给请求者.
3. 使用视图时需要进行两步操作
    1.定义视图
    2.配置URLconf
  1. Define Views

    1. Python is a view of the function, the application is defined in views.py.
    2. The first parameter is the view of an object of type HttpRequest reqeust, contains all information requests.
    3. View must return HttpResponse object, comprising response information returned to the requestor.
    4. HttpResponse need to import modules: from django.http import HttpResponse

    To write code file views:
    1. Import module HttpResponse
    from django.utils.httpwrappers Import HttpResponse
    2. Custom View function
    DEF index (Request):
    return HttpResponse ( 'the OK')

  2. URLconf configuration
    process to find the view:
    1. requestor in the browser address bar enter the URL, the request to the Web site.
    2. Site acquisition URL information.
    3. Then one by one and write URLconf good match.
    4. If a match is called correspondence [FIG.
    5. If no matches are found all URLconf successful. 404 then returns an error.
    1.URLconf inlet ----> settings file provided

Two steps are required to complete the URLconf configuration ----> settings in the file urls.py

1.在项目中定义URLconf

 还要导入   from django.conf.urls import url,include
 在urls文件中的url下面添加一句url ---> url(r'^',include('wen.urls'))


2.在应用中定义URLconf
提示:一条URLconf包括URL规则、视图两部分
 URL规则使用正则表达式定义.
	视图就是在 views.py 中定义的视图函数.

Create a new file in the file urls

下面这两句导入属于固定写法
from django.conf.urls import url
from wen.views import index

urlpatterns = [
		url(r'^$',index)  ----> 路由引导视图函数
]

Then in the http://127.0.0.1:8000/ page will directly enter in views.py written OK output

  1. Test: requesting access
    http://127.0.0.1:8000/ -> Output will be OK

Two steps required when using the view, two steps in no particular order

    1.配置URLconf
    2.在应用/views.py中定义视图

VII template
template in step
1. Create a template
2. Set template search path
3. view the incoming data received template
4. The template data processing

1. Create a template

1. 在应用同级目录下创建模板文件夹templates. 文件夹名称固定写法.
2.在templates文件夹下, 创建应用同名文件夹. 例, Book或者直接创建HTML文件,在HTML文件中写入数据做测试

2. Set the template search path
disposed in the path DIRS template TEMPLATES written under the path settings [os.path.join (BASE_DIR, 'templates' )]

In the back BASE_DIR caused to store the HTML file of your key clip

3. view template receiving incoming data
view template loaded

In views def file plus function return render (request, 'index.html' ) ----> Import also need to import the render django.shortcuts from
def index (Request):
return the render (Request, 'index.html' )

Then again or can be written in the current page:

def index(request):
    name = '如花'
    context = {
        'name':name
    }
    return render(request,'index.html',context)
然后再HTML文件中<h1>{{ name }}北京一卡通下大雨啊哈哈哈</h1>
加上两个大括号里面的参数就是上面的name  上面的name的如花就会传递到HTML文件里的name中

在测试访问
http://127.0.0.1:8000/  --->  会输出 “如花北京一卡通下大雨啊哈哈哈”

Eight cases
show a list of books

Implementation steps

1.创建视图
2.创建模板
3.配置URLconf

1. Create a view

1. 查询数据库数据
2. 构造上下文
3. 传递上下文到模板

# 定义视图:提供书籍列表信息
def bookList(request):
    # 查询数据库书籍列表数据
    books = BookInfo.objects.all()
    # 构造上下文
    context = {'books':books}
    # 数据交给模板处理,处理完成后通过视图响应给客户端
    return render(request, 'Book/booklist.html', context)

2. Create a template

1. 读取上下文数据
2. 构造网页html文档 : 书籍信息以列表样式展示
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>书籍列表信息</title>
</head>
<body>

<ul>

</ul>

</body>
</html>

3. Configure the URLconf
1. urls.py file into the application

from django.conf.urls import url
from book.views import index,bookList

urlpatterns = [
    url(r'^$',index),
    # 匹配书籍列表信息的URL,调用对应的bookList视图
    url(r'^booklist/$',bookList)
]

Nine, configuration and static files

Profiles

  1. Base_dir
    base_dir = os.path.dirname (os.path.dirname (os.path.abspath ( File )))
    current root directory of the project, Django will so to locate relevant documents in the project, we can also use this parameter to configuration file path.

  2. DEBUG
    Debug mode, after creating the initial project value is True, which is the default at work in debug mode.
    Role:
    Modify the code files, automatically restart
    when Django abnormal procedures, to the front display detailed error information to track
    down instead of debug mode, only return Server Error (500)

Note: Do not deploy line running Django run in modal mode, remember to modify the DEBUG = False and ALLOW_HOSTS.

  1. Local language and time zone
    Django support localization process, that is, the language and time zone support localization.
    Localization is the display language, and time using the local habits, localization here is carried out in China,
    Chinese mainland Simplified Chinese,
    time zone using the Time Zone Asia / Shanghai, pay attention to the time zone is not used here Beijing, he said.

    1. Engineering default language and time zone for the English and the UTC standard time zone
      LANGUAGE_CODE = 'en-us' # language
      TIME_ZONE = 'UTC' time zone # # Time zone

      2. Modify the language and time zone information to mainland China
      LANGUAGE_CODE = 'zh-Hans'
      TIME_ZONE = 'Asia / on Shanghai'

Static files
in order to provide static files, you need to configure two parameters:
STATICFILES_DIRS storage directory to find static files
STATIC_URL access static files URL prefix

Example:
1) Create a static directory under the project root directory to hold static files.
2) modify the static files in bookmanager / settings.py two parameters

STATIC_URL = ‘/static/’
STATICFILES_DIRS = [
os.path.join(BASE_DIR, ‘static’),
]

3) At this point in any static file can be used to add static URL / static / path of the file in the static to visit.

For example, we add a static index.html file to the directory, you can use 127.0.0.1:8000/static/index.html in a browser to access.

Or we added a subdirectory and file book / detail.html in static directory, you can use 127.0.0.1:8000/static/book/detail.html in a browser to access.

# django 是如何区分静态资源和动态中院的呢
# 就是通过 STATIC_URL
# 我们在访问静态资源 http://ip:port + STATIC_URL + 文件名
# django 就会认为我们是在访问静态资源,这个时候会去静态资源文件夹中进行匹配

App application configuration
in each application directory contains the apps.py file for relevant information to save the application.

When creating applications, Django will write a configuration class of the application to apps.py file, such as

from django.apps import AppConfig

class BookConfig(AppConfig):
name = ‘book’

We'll add these to the list of projects INSTALLED_APPS in settings.py, the show has registered install this application configuration properties.

1. AppConfig.name属性表示这个配置类是加载到哪个应用的,每个配置类必须包含此属性,默认自动生成。
2. AppConfig.verbose_name属性用于设置该应用的直观可读的名字,此名字在Django提供的Admin管理站点中会显示,如
from django.apps import AppConfig

class UsersConfig(AppConfig):
  name = 'book'
  verbose_name = '图书管理'

Guess you like

Origin blog.csdn.net/weixin_44074810/article/details/90740360