Ultra-detailed Django+vue+vscode front-end and back-end separation construction

1. Django backend construction

1.1 Create project and app
django-admin startproject tman
python manage.py startapp tadmin

insert image description here

1.2 Register app
INSTALLED_APPS = [
    'tadmin',
]
1.3 Run the project
python manage.py runserver
1.4 Configure mysql database
DATABASES = {
    
    
    'default': {
    
    
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'taskmanage',
        'USER': 'root',
        'PASSWORD': '密码',
        'HOST': '192.168.75.132',
        'PORT': '3306',
    }
}

Add the following code to init.py under the project tman project

pip install pymysql
import pymysql
pymysql.version_info = (1, 4, 3, "final", 0)
pymysql.install_as_MySQLdb()

insert image description here

1.5 Create a database class

Add the following code to model.py of tadmin

from django.db import models


class UserInfo(models.Model):
    username = models.CharField('用户名', max_length=128)
    password = models.CharField('密码', max_length=128)

    class Meta:
        verbose_name = '用户信息'
        verbose_name_plural = '用户信息'

    def __str__(self):
        return self.username

Execute the following command to create the database

python manage.py makemigrations
python manage.py migrate
1.6 Use Django background for data management

Add the following code in the tadmin application directory

from django.contrib import admin
from tadmin.models import UserInfo

admin.site.site_header = '任务管理系统'


class UserInfoAdmin(admin.ModelAdmin):
    list_display = ('id', 'username', 'password',)
    list_display_links = ('username',)
    list_per_page = 50


admin.site.register(UserInfo, UserInfoAdmin)

Create background administrator user

python manage.py createsuperuser

insert image description here

2. Django rest framework configuration

pip install djangorestframework
# 暂时不装也可以
pip install markdown
# 用于数据筛选
pip install django-filter

Register framework in settings

INSTALLED_APPS = [
    'rest_framework',
    'django_filters',
]
2.1 Serialization

Create serializer.py in the app directory and add the following code

from tadmin.models import UserInfo
from rest_framework import serializers


class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = "__all__"
2.2 Add View

Add the following code to view.py in the app directory:

from rest_framework.viewsets import ModelViewSet
from tadmin.models import UserInfo
from tadmin.serializer import UserInfoSerializer
from tadmin.filter import UserInfoFilter
from django_filters.rest_framework import DjangoFilterBackend


class UserInfoViewSet(ModelViewSet):
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer

    filter_class = UserInfoFilter
    filter_fields = ['username',]
    search_fields = ('username',)
2.3 Add route

Create a urls.py file in the app directory:

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from tadmin.views import UserInfoViewSet

router = DefaultRouter()
router.register('UserInfo', UserInfoViewSet, basename='UserInfo')

urlpatterns = [
]

urlpatterns += [
    path('', include(router.urls)),
]
2.4 Add the following code to urls in the root directory of the project
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/', include('tadmin.urls')),
]
2.5 API testing

http://127.0.0.1:8000/api/v1/UserInfo/

insert image description here

2.6 Filter and search function configuration

Create a filter.py file in the app root directory

from django_filters import FilterSet, filters
from tadmin.models import UserInfo


class UserInfoFilter(FilterSet):
    name = filters.CharFilter(field_name='username', lookup_expr='icontains')

    class Meta:
        model = UserInfo
        fields = ('username',)

Modify the view file in the app directory:在这里插入代码片

from django.shortcuts import render

from rest_framework.viewsets import ModelViewSet
from tadmin.models import UserInfo
from tadmin.serializer import UserInfoSerializer
from tadmin.filter import UserInfoFilter
from django_filters.rest_framework import DjangoFilterBackend


class UserInfoViewSet(ModelViewSet):
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer

    filter_class = UserInfoFilter
    filter_fields = ['username']
    search_fields = ('username',)

Register django_filters in settings:

INSTALLED_APPS = [
    'django_filters',
]

# REST_FRAMEWORK增加全局过滤配置  
REST_FRAMEWORK = {
    
      
 'DEFAULT_FILTER_BACKENDS': [  
     'django_filters.rest_framework.DjangoFilterBackend',
     'rest_framework.filters.SearchFilter',
 ],  
}
# 如果可以实现模糊查询,则以下语句可省略
FILTERS_DEFAULT_LOOKUP_EXPR = 'icontains'

The Filters icon appears on the Django Rest Framework page, indicating that the configuration is successful

insert image description here

2.7 Pagination settings

Make the following changes in settings.py

# REST_FRAMEWORK增加全局过滤配置  
REST_FRAMEWORK = {
    
      
    # 设置分页  
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',  
    'PAGE_SIZE': 10,
}

insert image description here
insert image description here

3. Automatically generate API documents

pip install drf-yasg

Make the following changes in the project folder urls.py

INSTALLED_APPS = [
    'drf_yasg',  # swagger
]

Make the following changes in the urls.py of the app

from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
    openapi.Info(
        title="API平台",
        default_version="v1",
        description="接口文档",
        terms_of_service="",
        contact=openapi.Contact(email='[email protected]'),
        license=openapi.License(name="BSD License"),
    ),
    public=True
)

router = DefaultRouter()
router.register('UserInfo', UserInfoViewSet, basename='UserInfo')

urlpatterns = [
    path('docs/', schema_view.with_ui('swagger',cache_timeout=0), name='schema-swagger-ui'),
]

Documentation to see if the document was successful,http://127.0.0.1:8000/api/v1/docs/

insert image description here

2. Vue front-end construction

1. Front-end tools and frameworks
  • node.js
  • npm
  • view 3
  • axios
  • Element plus
  • Front-end development tools: VS Code
2. Create a front-end file in the root directory of the Django project
npm init webpack tmanfront

The final file directory is as follows:

insert image description here

3. Modify the code in src/components/HelloWorld.vue as follows
<template>
    <div class="hello">
        <h1>{
    
    {
    
     msg }}</h1>
        <ul>
            <li v-for="(user,index) in users" :key="index" style="display: block;">
                {
    
    {
    
     index }}--{
    
    {
    
     user.username }}--{
    
    {
    
     user.password }}
            </li>
        </ul>
        <form action="">
            用户名:<input type="text" placeholder="user name" v-model="inputUser.username"><br>

            密码:<input type="text" placeholder="user password" v-model="inputUser.password"><br>
            <button type="submit" @click="userSubmit()">提交</button>
        </form>
    </div>
</template>

<script>
import {
    
     getUsers,postUser } from '../api/api.js';
export default {
    
    
    name:'hellouser',
    data () {
    
    
        return {
    
    
            msg:'Welcome to Your Vue.js App',
            users:[
                {
    
    username:'test1',password:'test1'},
                {
    
    username:'test2',password:'test2'}
            ],
            inputUser:{
    
    
                "username":"",
                "password":"",
            }
        }
    },
    methods:{
    
    
        loadUsers(){
    
    },
        userSubmit(){
    
    }
    },
    created: function(){
    
    
        this.loadUsers()
    }
}
</script>

Start the front-end project, visit 127.0.0.1:8080 in the browser, you can see that the page just written has been updated

insert image description here

4. Front-end and back-end joint debugging

Use the django-cors-headers module to solve cross-domain problems

pip install django-cors-headers

Then add this module in project settings.py:

INSTALLED_APPS = [
    'corsheaders',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware', # 需注意与其他中间件顺序,这里放在最前面即可
    ...
]
# 支持跨域配置开始
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True 

The back-end part is in the paragraph. Next, we need to add the front-end logic. The Vue framework generally uses the axios module to make network requests. This method is used here. The following is the operation in the front-end project: First, install the axios module on the command line.
If Install with npm without installing cnpm:

cnpm install axios
或者
npm install axios

In order to facilitate the management of various logics of api requests, create an api directory under the src directory of the front-end project, and then create api.js and index.js files. The index.js file configures axios:
/src/api/index.js

import Vue from 'vue'
import Axios from 'axios'

const axiosInstance=Axios.create({
    
    
    withCredentials:true
})

axiosInstance.interceptors.request.use((config)=>{
    
    
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    const regex = /.*csrftoken=([^;.]*).*$/
    config.headers['X-CSRFToken'] = document.cookie.match(regex) === null ? null : document.cookie.match(regex)[1]
    return config
})

axiosInstance.interceptors.response.use(
    response=>{
    
    
        return response
    },
    error=>{
    
    
        return Promise.reject(error)
    }
)

Vue.prototype.axios=axiosInstance

export default axiosInstance

The api.js file makes a request to the backend. You can see that obtaining the books list and adding a book each correspond to a request:

import axiosInstance from "./index";

const axios = axiosInstance
export const getUsers = () => {
    
     return axios.get(`http://127.0.0.1:8000/api/v1/UserInfo/`) }

export const postUser = (username, password) => {
    
     return axios.post(`http://127.0.0.1:8000/api/v1/UserInfo/`, {
    
     'username': username, 'password': password }) }

Then update the processing logic in HelloWorld.vue:

<template>
    <div class="hello">
        <h1>{
    
    {
    
     msg }}</h1>
        <ul>
            <li v-for="(user,index) in users" :key="index" style="display: block;">
                {
    
    {
    
     index }}--{
    
    {
    
     user.username }}--{
    
    {
    
     user.password }}
            </li>
        </ul>
        <form action="">
            用户名:<input type="text" placeholder="user name" v-model="inputUser.username"><br>

            密码:<input type="text" placeholder="user password" v-model="inputUser.password"><br>
            <button type="submit" @click="userSubmit()">提交</button>
        </form>
    </div>
</template>

<script>
import {
    
     getUsers,postUser } from '../api/api.js';
export default {
    
    
    name:'hellouser',
    data () {
    
    
        return {
    
    
            msg:'Welcome to Your Vue.js App',
            users:[
                {
    
    username:'test1',password:'test1'},
                {
    
    username:'test2',password:'test2'}
            ],
            inputUser:{
    
    
                "username":"",
                "password":"",
            }
        }
    },
    methods:{
    
    
        loadUsers(){
    
    
            getUsers().then(response=>{
    
    
                this.users=response.data
            })
        },
        userSubmit(){
    
    
            postUser(this.inputUser.username,this.inputUser.password).then(response=>{
    
    
                console.log(response)
                this.loadUsers()
            })
        }
    },
    created: function(){
    
    
        this.loadUsers()
    }
}
</script>

So far, a simple Django+vue front-end and back-end separation project has been built, and the test adds data successfully

insert image description here
insert image description here

It can be seen that the data in the list is read from the backend, and the submission database of the frontend can also have corresponding operations, so the frontend and backend are now connected.

5. Front-end packaging

At this stage, the front and back ends are developed separately, but when it is finally used, the code needs to be combined.
First, package the front-end project. Here, use Vue’s automatic packaging and enter the root directory of the front-end:

npm run build

insert image description here

You can see that there is an extra distfolder in the front-end project, which is the packaging result of the front-end files. distThe folder needs to be copied tmaninto the project folder

insert image description here

Then modify the settings.py file accordingly, in fact, it is to help django specify the search address of template files and static files:

TEMPLATES = [
    {
    
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'dist')],
        ...
    },
]
...
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'dist/static'),
]

Finally, configure the corresponding route of the entry html file in the project root urls.py file:

from django.views.generic.base import TemplateView
urlpatterns = [
    path('', TemplateView.as_view(template_name='index.html'))
]

Restart the project, and this time use a browser to access 127.0.0.1:8000, that is, the corresponding port of the django service.
It can be seen that the interaction of the project is normal and meets our expectations.

insert image description here

3. Summary

This article takes a very simple demo as an example to introduce django+drf+vuethe development mode of front-end and back-end separation, which can basically be regarded as a hands-on introduction. With this small demo, whether it is the front-end page or the back-end function, it can be extended accordingly, so as to develop a more complex website.

Guess you like

Origin blog.csdn.net/weixin_43883625/article/details/130190149