跳至主要内容

django 详细介绍



网站示例

wagtail
是一个用Python编写的免费开源 内容管理系统(CMS),在使用Django框架的网站中很流行

pdf文档下载

Django使您可以更轻松地以更少的代码更快地构建更好的Web应用程序

Django软件包是Django项目中可重复使用的应用程序,网站,工具等的目录https://djangopackages.org/

https://www.djangosites.org/

•  GeoDjango: 定制的GIS Web框架 
•  Django Debug Toolbar:调试工具 
•  Django Easy Maps: 地图显示工具 
•  Django Haystack: 模块化搜索工具








To create a Django application that performs CRUD operations, follow the following steps.

1. Create a Project $ django-admin startproject crudexample
2. Create an App $ python3 manage.py startapp employee
3. Project Structure
4.Run the command to migrate the migrations.$ python3 manage.py migrate
5.Run Server To run server use the following command.$ python3 manage.py runserver

Access to the Browser Access the application by entering localhost:8000/show, it will show all the available employee records. Initially, there is no record.

Adding Record Click on the Add New Record button and fill the details.

This section also allows, update and delete records from the actions column. After saving couple of records, now we have following records.

Update Record Lets update the record of x by clicking on edit button. It will display record of x in edit mode.

Lets, suppose I update x to x kumar then click on the update button. It updates the record immediately. Click on update button and it redirects to the following page. See name is updated. Same like, we can delete records too, by clicking the delete link.

Delete Record Suppose, I want to delete x, it can be done easily by clicking the delete button.


框架的名称受到比利时著名的吉普赛爵士吉他手Django Reinhardt的艺名的启发,因此为该框架创建了许多便捷附件的开发人员将他们称为Jazzband

对于ABC版本的Django,AB代表功能版本,C代表补丁版本
例如:Django version 2.1.3
2.1 is a number of feature release(功能版本
3 is a number of patch release(补丁版本

LTS: Long-Term Support (长期支持)软件开发中的著名标准。这意味着开发人员将在更长的时间内支持该版本的框架(对于Django,通常为3年或更长时间),您可以安全地将版本更新到较新的修补程序版本,而不必担心会破坏与源代码的兼容性

Django采用了MVT的软件设计模式,即模型(Model),视图(View)和模板(Template)

Model-View-Controller(MVC的主要思想是将责任划分为三个部分。模型部分包含业务逻辑,视图代表应用程序,控制器管理两个逻辑之间的数据流

Model -->        my_app/models.py
View -->           my_app/templates/my_app/index.html
Controller -->  my_app/views.py

在商店应用程序中,它可以是客户,产品和购买商品;在博客中,业务对象可以是作者,帖子和评论。

Django默认提供User 和 Group模型,来自django.contrib.auth.models

在cmd中创建虚拟环境
python -m venv web
激活虚拟环境
web\scripts\activate.bat
退出虚拟环境
deactivate



先安装django后创建项目
pip install django==3.0.2
要创建项目和第一个应用程序,请在命令行中运行以下命令
django-admin startproject magazine
cd magazine
django-admin startapp blog
mkdir blog\templates\blog

magazine/
├── blog
    ├── ...
    ├── models.py    # Model
    ├── views.py     # Controller
    └── templates    # View
        └── blog
            └── index.html
├── magazine
    ├── ...
    └── urls.py      # Controller
└── templates        # View
    └── base.html


为应用程序创建“templates”目录时
应将其命名为“<application name>/templates/<application name>”

你有 blog/templates/index.html and shop/templates/index.html 文件,其中blog和shop是项目中的应用程序。这种布局的主要缺陷是什么?
Django template loader返回找到的第一个"index.html" 。因此,您无法控制自己得到哪一个

magazine\blog\templates\blog\index.html
<!DOCTYPE html>
<title>Movies</title>
 
<h1>Films by {{ director }}</h1>
 
<ul>
{% for movie in movies %}
  <li>{{ movie.year }} - {{ movie.title }}</li>
{% endfor %}
</ul>

magazine\blog\views.py
from django.conf import settings
from django.shortcuts import render
from django.views import View
 
movies = [
    {
        'title''Catchfire',
        'year'1990,
    },
    {
        'title''Mighty Ducks the Movie: The First Face-Off',
        'year'1997,
    },
    {
        'title''Le Zombi de Cap-Rouge',
        'year'1997,
    },
]
 
 
class MovieView(View):
    def get(self, request, *args, **kwargs):
        return render(
            request, 'blog/index.html', context={
                'director': settings.DIRECTOR,
                'movies': movies,
            }
        )



# magazine\magazine\urls.py
from django.urls import path
from blog.views import MovieView
 
urlpatterns = [
    path('', MovieView.as_view()),
]



magazine\magazine\settings.py中修改INSTALLED_APPS变量添加变量DIRECTOR
INSTALLED_APPS = [
    ...
    'blog',
]


DIRECTOR = 'James'



在<project_name>/settings.py文件中,您仅定义Variables变量,而不编写任何函数或类
BASE_DIR -->               The root of your project
INSTALLED_APPS -->    All the applications you wish to use
DATABASES  -->           Configuration of databases
ALLOWED_HOSTS -->     The hostnames for your server

开发服务器如果出现问题,您想显示回溯和其他有用信息。您可以DEBUG = True在settings.py模块中添加调试模式,生产服务器时,强烈建议设置DEBUG = False。

IS_RELEASE_SERVER = input().lower() == 'true'
DEBUG = not IS_RELEASE_SERVER

# 启动本地服务器
python manage.py runserver
等同于python manage.py runserver 8000


浏览器打开http://127.0.0.1:8000/

Controller由两种类型的文件组成:"views.py" and "urls.py".
在"urls.py"中,定义服务的路由。 Routing 是将请求链接与适当的视图处理程序进行匹配的过程

在"views.py"中定义了视图处理程序,它们在模型和视图之间扮演中介者的角色。一个视图处理程序是一个函数或一个类来响应请求。由于客户端和服务器之间的通信是HTTP协议的一种实现,因此处理程序将使用状态码进行回答


http状态码

让我们看看在有网站请求时它们如何交互。

#用户在视图中看到链接或按钮,然后按它并创建请求。
1. A user sees a link or a button in a View, presses it and creates a request.

#控制器收到请求。
2. The Controller receives the request. 

#它将请求传递给适当的处理程序。
3. It passes the request to the appropriate handler.

#处理程序调用Model方法从数据存储中检索对象。
4. The handler calls Model methods to retrieve objects from data storage.

#选择View模板以呈现响应。
5. It chooses the View template to render a response.

#用户看到响应。
6. A user sees a response.

 





每当我们创建模型,删除模型或更新我们项目的任何models.py中的任何内容时。我们需要运行两个命令makemigrationsmigratemakemigrations基本上会为预安装的应用程序(可以在settings.py中的已安装应用程序中查看)和您在已安装的应用程序中添加的新创建的应用程序模型生成SQL命令,而migration会在数据库文件中执行这些SQL命令。









评论

此博客中的热门博文

Mongo 入门

https://pymongo.readthedocs.io/en/stable/tutorial.html https://www.mongodb.com/languages/python https://zhuanlan.zhihu.com/p/51171906 https://www.runoob.com/python3/python-mongodb.html https://blog.baoshuo.ren/post/luogu-spider/ https://hub.docker.com/_/mongo 安装 MongoDB $ docker search mongo 启动一个mongo服务器实例 $ docker run --name some-mongo -d mongo:tag some-mongo是您要分配给容器的名称,tag是指定您想要的 MongoDB 版本的标签 MongoDB 的默认数据目录路径是/data/db 如下: $ docker run -it -v mongodata:/data/db -p 27017:27017 --name mongodb --restart unless-stopped -d mongo 你应该让 MongoDB 在端口 27017 上运行,并且可以通过localhostWindows 和 Ubuntu 20.04 上的URL访问 http://localhost:27017/ -p 是 HOST_PORT:CLIENT_PORT  -P 随机端口 -p 27017:27017 :将容器的27017 端口映射到主机的27017 端口 -v mongodata:/data/db :将主机中当前目录下的db挂载到容器的/data/db,作为mongo数据存储目录 从另一个 Docker 容器连接到 MongoDB 镜像中的 MongoDB 服务器侦听标准 MongoDB 端口27017,因此通过 Docker 网络连接将与连接到远程mongod. 以下示例启动另一个 MongoDB 容器实例,并mongo针对上述示例中的原始 MongoDB 容器运行命令行客户端,从而允许您针对数据库实例执行 MongoDB 语句: $ docker run -it --network some-network --...

MechanicalSoup

用于自动与网站交互的 Python 库。 MechanicalSoup 自动存储和发送 cookie,跟踪重定向,并且可以跟踪链接和提交表单。 它不执行 JavaScript。 https://github.com/MechanicalSoup/MechanicalSoup https://mechanicalsoup.readthedocs.io/en/stable/index.html https://realpython.com/python-web-scraping-practical-introduction/ pip show Mechanicalsoup 找到模块的安装位置 https://stackoverflow.com/questions/54352162/download-file-with-mechanicalsoup # Install dependencies # pip install requests # pip install BeautifulSoup4 # pip install MechanicalSoup # Import libraries import mechanicalsoup import urllib.request import requests from bs4 import BeautifulSoup import re # Create a browser object that can collect cookies browser = mechanicalsoup.StatefulBrowser() browser.open("https://www.ons.gov.uk/economy/grossdomesticproductgdp/timeseries/l2kq/qna") browser.download_link(link_text=".xls",file="D:/ONS_Data.xls" )

端口映射 公网访问内网

https://portforward.com/ Holer 通过安全隧道将位于NAT和防火墙之后的本地服务器暴露给公共Internet。 Holer是一个将原型中的应用映射到公网访问的端口映射软件,支持转发基于TCP协议的报文 https://github.com/wisdom-projects/holer 方式一:使用(公告)的holer映射或者开通holer服务,通过holer客户端软件经 holer服务器实现公网访问。 公开的holer映射详情如下: 访问密钥 访问域名 公网地址 本地地址 使用场景 HOLER_CLIENT-2F8D8B78B3C2A0AE holer65530.wdom.net holer.org:65530 127.0.0.1:8080 网页 HOLER_CLIENT-3C07CDFD1BF99BF2 holer65531.wdom.net holer.org:65531 127.0.0.1:8088 网页 HOLER_CLIENT-2A623FCB6E2A7D1D holer65532.wdom.net holer.org:65532 127.0.0.1:80 网页 HOLER_CLIENT-AF3E6391525F70E4 不适用 holer.org:65533 127.0.0.1:3389 远程桌面 HOLER_CLIENT-822404317F9D8ADD 不适用 holer.org:65534 127.0.0.1:22 SSH协议 HOLER_CLIENT-27DD1389DF1D4DBC 不适用 holer.org:65535 127.0.0.1:3306 数据库 使用Java版本的holer客户端 ①java 1.7或者更高版本 ②下载holer-client.zip 修改配置文件C:\holer-client\conf\holer.conf HOLER_ACCESS_KEY=HOLER_CLIENT-2A623FCB6E2A7D1D HOLER_SERVER_HOST=holer65532.wdom.net ③建议先双击运行C:\holer-client\bin\shutdown.bat,再双击运行C:\holer-client\bin\startup.bat...