Django project practice (mall): 1. Project preparation

Insert picture description here

(According to the content of teacher's live broadcast)

1. Project introduction

  • In this project, complete the development of e-commerce mall and develop a simplified mall similar to Taobao

1. Introduction to the project development process

Insert picture description here

1.1 Architecture design

  • Analysis of possible technical points
  • Whether the front and rear ends are separated
  • Which frameworks are used on the front end
  • Which frameworks are used in the backend
  • What database to choose
  • How to implement caching
  • Whether to build a distributed service
  • How to manage source code

1.2 Database design

  • The design of the database table is very important
  • According to project requirements, design appropriate database tables
  • If the database table is unreasonably designed in the early stage, it will become difficult to maintain as the demand increases in the later stage

1.3 Integration test

  • Pay attention to the bug report of the test feedback platform during the testing phase

2. Project demand analysis

2.1 Reasons for demand analysis:

  • Can understand the business process and main business requirements of the project as a whole.
  • In the project, demand-driven development. That is, developers need to achieve business logic with requirements as the goal.

2.2 Requirement analysis method:

  • In the enterprise, the demand is analyzed with the help of product prototype diagrams.
  • After the requirements analysis is completed, the front-end develops the front-end page according to the product prototype diagram, and the back-end develops the corresponding business and response processing.

2.3 Contents of demand analysis:

  • Pages and their business processes and business logic.

2.4 Main steps

2.4.1 Introduction to the main page of the project (omitted)

2.4.2 Summary of the main modules of the project

Module Features
verification Graphic verification, SMS verification
user Registration, login, user center
worth mentioning QQ login
Homepage ad Homepage ad
Product Product list, product search, product details
shopping cart Shopping cart management, shopping cart merging
Order Confirm order, submit order
Pay Alipay payment, order product evaluation
MIS system Data statistics, user management, authority management, merchandise management, order management

3. Project structure design

3.1 Project development model

  • The development model of this project is as follows:
Options Technology selection
Development model No separation of front and rear
Back-end framework Django
Front-end framework Vue.js
  • Description
    • The development model that does not separate the front and back ends is to improve search engine rankings, that is, SEO. Especially the homepage, detail page and list page.
    • The page needs to be partially refreshed: we will choose to use Vue.js to achieve it.

3.2 Project operation mechanism

Insert picture description here

2. Project creation and configuration

1. Preparation

1.1 Create a virtual environment of the mall

  • Create a directory for the project and enter, execute pipenv shell
pipenv shell

1.2 Install the Django framework and related packages

# 安装django环境
pip install django==2.2
# 安装mysql驱动
pip install mysqlclient 
# 安装redis驱动
pip install django-redis

1.3 Create a Django project in Meido Mall

django-admin startproject lgshop
  • If you run it now, the following prompt appears
    Insert picture description here
    . Change the script paramenters parameter of run/debug configurations to runserver
    Insert picture description here

1.4 Other preparations

  • mysql database preparation: mysql 5.7
  • Redis database preparation: redis 2.1

2. Configure the development environment

  • The project environment is divided into development environment and production environment.
    • Development environment: used to write and debug project code.
    • Production environment: used for online deployment and operation of the project.

2.1 Specify the development environment configuration file

  • When django creates the project, it automatically specifies the configuration file in the main() function of manager.py, and modify it to the configuration file specified by yourself
    Insert picture description here
def main():
    """Run administrative tasks."""
    # django默认的配置文件
    # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lgshop.settings')
    # 开发环境的配置文件
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lgshop.dev')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

  • Note: It will only be used when the wsgi.py project is officially launched, and can be ignored during development, but should not be deleted

2.2 Configure MySQL database

  • Modify the configuration file: The development environment configuration file of this project is dev.py
    Insert picture description here
DATABASES = {
    'default': {
        # 'ENGINE': 'django.db.backends.sqlite3',
        # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        # mysql 版本 5.7
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'lg_shop',  # 数据库名字
        'USER': 'root',  # 数据库用户名
        'PASSWORD': 'root',  # 数据库密码
        'HOST': '127.0.0.1',  # 数据库地址   
        'PORT': 3306  # 数据库端口号
    }
}
  • Need to create mysql database root/root@lg_shop
    Insert picture description here

2.3 Configure redis database

  • The default redis can be set to database 0 (can be changed)
  • Session can save the No. 1 database
  • If other data is saved in other libraries.
  • Each time you add one, you can rename one and modify related parameters
    Insert picture description here
# Redis缓存 0-15  16
CACHES = {
    
    
    "default": {
    
    
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/0",
        "OPTIONS": {
    
    
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "session": {
    
    
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
    
    
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

2.4 Configure project log

  • Configuration project log purpose: use log files to record website output information
    Insert picture description here
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,  # 是否禁用已经存在的日志器
    'formatters': {  # 日志信息显示的格式
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
        },
    },
    'filters': {  # 对日志进行过滤
        'require_debug_true': {  # django在debug模式下才输出日志
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {  # 日志处理方法
        'console': {  # 向终端中输出日志
            'level': 'INFO',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {  # 向文件中输出日志
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'logs/lgshop.log'),  # 日志文件的位置
            'maxBytes': 300 * 1024 * 1024,
            'backupCount': 10,
            'formatter': 'verbose'
        },
    },
    'loggers': {  # 日志器
        'django': {  # 定义了一个名为django的日志器
            'handlers': ['console', 'file'],  # 可以同时向终端与文件中输出日志
            'propagate': True,  # 是否继续传递日志信息
            'level': 'INFO',  # 日志器接收的最低日志级别
        },
    }
}
  • Create a logs directory on the root directory

2.4 Configure front-end static files

  • You need to use static files in mall projects, such as css, images, js, etc.

2.4.1 Prepare static files

Create a new static directory under the project directory

2.4.2 Specify static file loading path

Insert picture description here

# ./lgshop/dev.py 
# 指定加载静态文件的路径前缀
STATIC_URL = '/static/'

# 静态文件加载路径
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

2.5 Configuration template file

2.5.1 Prepare template files

Create a new templates directory under the project directory

2.5.2 Specify the template file loading path

Insert picture description here

# ./lgshop/dev.py 
TEMPLATES = [
    {
    
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
    
    
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

3. Set the guide package path

  • In order to facilitate the management of all applications, create an apps directory to store all applications

3.1 Create a user module sub-application

-Example to create users application
Insert picture description here

python ..\manage.py startapp users 

3.2 Define a view method for users

Insert picture description here

# ./apps/user/views.py
from django.shortcuts import render
from django.views import View

class RegisterView(View):
    def get(self, request):
        """提供用户注册页面"""
        return render(request, 'register.html')
  • Note: Create register.html in the ./templates/ directory

3.3 Register app

  • There are two methods: direct registration; set the package guide path registration

3.3.1 Direct registration

Insert picture description here

3.3.2 Set the guide package path registration

Insert picture description here

  • Note: View the guide package path: print(sys.path)

3.4 Register application routing

  • Either register the route in the app or register the total route first

3.2.1 Register the route inside the application

Insert picture description here

# ./apps/users/urls.py 
from django.urls import path
from . import views

app_name = 'users'

urlpatterns = [
    # 注册
    path('register/', views.RegisterView.as_view(), name='register'),
]

3.2.2 Register the total route

Insert picture description here

# ./lgshop/urls.py
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', include('apps.users.urls')),
]

4. Related directories and files

Insert picture description here

Guess you like

Origin blog.csdn.net/laoluobo76/article/details/112935168