Django builds a personal blog platform 2---create a Django project and project combing

Article Directory

Django builds a personal blog platform 2-create a Django project and project combing

It is assumed that you have a certain understanding of Django and master certain related technologies. If not, please watch one of my previous articles.

MVC and MTV framework

MVC

The web application is divided into three layers: model (M), view (V), and controller (C), which are connected in a plug-in and loosely coupled manner. The model is responsible for the mapping (ORM) between business objects and the database, the view is responsible for the interaction with the user (page), and the controller receives the user's input and calls the model and view to complete the user's request.

image-20201110110214121

MTV

Django's MTV mode is essentially the same as MVC, and it is also for maintaining loose coupling between components, but with a slightly different definition. Django's MTV is the value:

  • M stands for Model: Responsible for the relational mapping (ORM) between business objects and databases.
  • T stands for Template: Responsible for how to display the page to the user (html).
  • V stands for View: Responsible for business logic, and call Model and Template when appropriate.

In addition to the above three layers, a URL distributor is also needed. Its function is to distribute the page requests of each URL to different Views for processing. The View then calls the corresponding Model and Template. The response mode of MTV is as follows:

img

Generally, the user initiates a request to our server through the browser. This request goes back to access the view function. (If there is no data call involved, then the view function returns a template that is a web page to the user at this time), the view function The model is called, the model searches the database for data, and then returns step by step. The view function fills the returned data into the blanks in the template, and finally returns the web page to the user.

Create a Django project

You need to install pycharm first and go to the official website to download it.

Open pycharm

File—>New Project

image-20210518155954783

The role of directory structure

The main directory structure is as follows after successful creation:

image-20210518161109155

Directory function

MyBlog-----------------项目名
	blog---------------应用名
		migrations-----数据库迁移文件
		admin.py-------后台管理
		models.py------模型文件(表结构)
		views.py-------视图函数(ORM增删改查)
	MyBlog-------------项目目录(配置文件)
		settings.py----配置文件
		urls.py--------路由配置
		wsgi.py--------静态文件转发(部署时会用到)
	templates----------模板文件(html)
	manage.py----------项目运行

run

Click the run button in the upper right corner, open the browser and visit http://127.0.0.1:8000/ to see that the rocket proves successful.

image-20201110112542922

A brief walk through the process

A simple example based on Django

  1. url controller (find it in the first step)
#找对应的函数,是哪个app里面的函数
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls), #这个先不用管,后面会学
    path('index/',views.index),
]
  1. Create login.html in templates
<!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">
    <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim 和 Respond.js 是为了让 IE8 支持 HTML5 元素和媒体查询(media queries)功能 -->
    <!-- 警告:通过 file:// 协议(就是直接将 html 页面拖拽到浏览器中)访问页面时 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/html5shiv.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/dest/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<h1>欢迎来到登录页面!</h1>
<form action="">
    用户名:<input type="text" name="username">
    密码:<input type="text" name="password">
    <input type="submit">
</form>

<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
</body>
</html>
  1. views view
# Create your views here.


def index(request):
    return render(request, 'login.html')
  1. After startup, enter localhost/index in the browser to access

get request to get data

# print(request.GET)  # <QueryDict: {'username': ['laowang'], 'password': ['123']}>
username = request.GET.get('username')
password = request.GET.get('password')
if username == 'laowang' and password == '123':
    return HttpResponse('登录成功!')
else:
    return HttpResponse('登录失败!')

post request to get data

Turn off an authentication mechanism first, in the settings configuration file

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',
]
if request.method == 'GET':
    return render(request, 'login.html')
else:
    username = request.POST.get('username')
    password = request.GET.get('password')
    if username == 'laowang' and password == '123':
        return HttpResponse('登录成功!')
    else:
        return HttpResponse('登录失败!')

Write project

1. 创建项目  first_project
2. 创建app  app01
做一个登录页面的Web项目,浏览器输入一个网址得到一个Web页面

用户: http:127.0.0.1:8000/login/
1. urls.py
    urlpatterns = [
        # url(r'^admin/', admin.site.urls),
        url(r'^index/', views.index),  # 配置路径
    ]
2. 写逻辑视图views.py
    def index(request):  # HttpRequest
        # # print(request.GET)  # <QueryDict: {'username': ['laowang'], 'password': ['123']}>
        # username = request.GET.get('username')
        # password = request.GET.get('password')
        # if username == 'laowang' and password == '123':
        #     return HttpResponse('登录成功!')
        # else:
        #     return HttpResponse('登录失败!')
        # request.method  GET POST
        if request.method == 'GET':
            return render(request, 'login.html')
        else:
            username = request.POST.get('username')
            password = request.GET.get('password')
            if username == 'laowang' and password == '123':
                return HttpResponse('登录成功!')
            else:
                return HttpResponse('登录失败!')
3. 创建html文件
	在templates文件架中创建一个login.html文件
	<!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">
        <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
        <title>Bootstrap 101 Template</title>

        <!-- Bootstrap -->
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

        <!-- HTML5 shim 和 Respond.js 是为了让 IE8 支持 HTML5 元素和媒体查询(media queries)功能 -->
        <!-- 警告:通过 file:// 协议(就是直接将 html 页面拖拽到浏览器中)访问页面时 Respond.js 不起作用 -->
        <!--[if lt IE 9]>
          <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/html5shiv.min.js"></script>
          <script src="https://cdn.jsdelivr.net/npm/[email protected]/dest/respond.min.js"></script>
        <![endif]-->
    </head>
    <body>
    <h1>欢迎来到登录页面!</h1>
    <form action="/index/" method="post">
        用户名:<input type="text" name="username">
        密码:<input type="text" name="password">
        <input type="submit">
    </form>

    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
    </body>
    </html>

Project preliminary integration structure

Static file configuration

Create a folder under the project folder to store static files, such as jingtaiwenjian, generally we call static

Create another css folder under the static (if you call jingtaiwenjian) folder

Write under the settings.py file

STATIC_URL = '/static/' # 别名,一般都起static
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
    # os.path.join(BASE_DIR, 'jingtaiwenjian'),
]

Route distribution

I did not do routing distribution here, because there is no such demand. You can distribute it if you need it.

Distribution steps:

# second_project/urls.py
urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^app01/', include('app01.urls')),
    url(r'^app02/', include('app02.urls')),
]
# app01/urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),

]
# app02/urls.py
from django.conf.urls import url
from django.contrib import admin
from app02 import views

urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^home/', views.home),

]

Database configuration

First of all, you have to install the mysql database, you won’t read my other blog:

In the settings.py file, comment out the original and add mysql

To create a database named xxx in the database

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#     }
# }

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'xxx',   # 数据库名
        'USER': 'root',
        'PASSWORD': '***',
        'HOST': '127.0.0.1',
        'PORT': 3306,
        'OPTIONS': {'charset': 'utf8mb4'},
    }
}

There is also the configuration of redis, which acts as a cache. We'll talk about it when we get down to the cache.

Time zone and language

The time zone is changed to Asia Shanghai, and the admin background language is displayed as Chinese.

LANGUAGE_CODE = 'zh-Hans'

# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False

Afterword

My blog is currently running normally. This is the record and summary of my own blog website. If you follow my tutorial, there will generally be no problems, but there will always be bugs. If you encounter problems, welcome to communicate with me.

Finally, if you think this article is useful to you, welcome one-click three-link , as appropriate , thank you!