Addition, deletion and modification of Django

1. New django project

Create a project using pycharm

file---newProject

 

Create a project using the command

django-admin startproject projectname

 

2. New app

python manage.py startapp app01

 

3. Configure settings Py, in settings Configure app in py, switch language and time zone, and switch database to mysql,

INSTALLED_APPS = [
    ...
    'app01.apps.App01Config',
]
LANGUAGE_CODE = 'zh-hans'  # language
​
TIME_ZONE = 'Asia/Shanghai'  # time zone
​
USE_TZ = False  # Make the modified time zone effective
​
# Configuration database
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # Engine, using mysql
        'NAME': 'day04',   # Database name
        'USER': 'root',  # Login user name of the database
        'PASSWORD': 'root1234',  # Password for database login
        'HOST': '127.0.0.1',  # Host where the database is located
        'PORT': 3306,  # Port number used by the database
    }
}

It needs to be in settings In the directory where py is located, init Py, write the following

import pymysql
pymysql.install_as_MySQLdb()

 

4. Cross domain configuration at the back end

What is a cross domain problem?

It means that the browser cannot execute scripts of other websites. It is caused by the homology policy of the browser and the security restriction imposed by the browser.

The so-called homology means that the domain name, protocol and port are the same. As long as there is one difference, it is cross domain.

django backend cross domain

  • Install Django CORS headers

    pip install django-cors-headers
    ​
    # pip show module name to check whether a module has been installed
    pip show django-cors-headers
  • In settings Py installed_ Configure in apps

    INSTALLED_APPS = [
        # Third party package
        'corsheaders',  # Cross domain
        'app01.apps.App01Config',
    ]
  • In settings PY

    MIDDLEWARE = [
        'django.contrib.sessions.middleware.SessionMiddleware',
        # Cross domain configuration is performed here, and in the third line of middleware
        'corsheaders.middleware.CorsMiddleware',
        'django.middleware.common.CommonMiddleware',
        # Comment out the csrf line, line 5
        # 'django.middleware.csrf.CsrfViewMiddleware',
    ]
  • In settings Add variables to py to allow all source access

    CORS_ALLOW_ALL_ORIGINS = True  # Allow access to all sources

5. Configure the app under the main route for route distribution

from django.contrib import admin
from django.urls import path, include
​
urlpatterns = [
    path('admin/', admin.site.urls),
    path('app01/', include('app01.urls'))
]
​
# app01/urls.py
from django.urls import path
from . import views
​
urlpatterns = [
    
]

6. In models Designing news classification table in PY

from django.db import models
​
# Create your models here.
​
​
# In models Every new class created under py means a new table is created in the database
class Cate(models.Model):
    # Class is the field in the table
    name = models.CharField(max_length=32)
​
    def __str__(self):
        return self.name

7. Generate and execute migration files

python manage.py makemigrations
​
python manage.py migrate

 

9. Add classification interface

from django.views import View
from django.http import JsonResponse
​
from .models import Cate
​
​
class CateView(View):
​
    def post(self, request):
        # Get web submission data
        name = request.POST.get('name')  # None
        # Judge whether the data is complete. If you don't get the data, a message will be returned. The data is incomplete
        if not name:
            return JsonResponse({'msg': 'Incomplete data', 'code': 400}, json_dumps_params={'ensure_ascii': False})
        # If you get the data, add
        Cate.objects.create(name=name)
        return JsonResponse({'msg': 'Added successfully', 'code': 200}, json_dumps_params={'ensure_ascii': False})
​

10. Add route

from django.urls import path
from . import views
​
urlpatterns = [
    path('cate/', views.CateView.as_view()),  # Category addition, deletion, modification and query
]

 

11. Classification interface document

Request address: http://127.0.0.1:8000/app01/cate/

Request method: post

Request parameters:

fieldtypeRequired
namestringtrue

Return data:

# Prompt when the request fails and the data is empty
{
    'msg': 'Incomplete data',
    'code': 400
}
# Request succeeded
{
    'msg': 'Added successfully',
    'code': 200
}

 

12. Under vue, create addcate vue page to realize the function of page form

Create vue: vue init webpack myvue

Install axios: cnpm install --save axios

1. Configure global axios

Under src folder, main JS

import axios from 'axios'
Vue.prototype.axios = axios
axios.defaults.baseURL = 'http://127.0.0.1:8000'

2. Create addcate. Under components under src Vue page

<template>
    <div>
        <!-- Write a form to add categories here -->
        <div>
            <form action="">
                <p>Classification Name: <input type="text" v-model="name"></p>
                <p><button>add to</button></p>
            </form>
        </div>
    </div>
</template>
​
<script>
export default {
    data() {
        return {
            name: ''
        }
    },
    methods: {
​
    },
    created() {
​
    }
}
</script>
​
<style scoped>
​
</style>
​

 

13. Explanation of execution process of django+vue + browser

 

Display data

1. Display data interface

class CateView(View):
​
    def get(self, request):
        # 1. Get all the data
        cate_list = Cate.objects.all()
        # 2. Turn the obtained data into a list
        cate_data = [{'id': i.id, 'name': i.name} for i in cate_list]
        # 3. The returned data is returned in json
        return JsonResponse(cate_data, safe=False, json_dumps_params={'ensure_ascii': False})

2. Display data interface documents

Request address: http://127.0.0.1:8000/app01/cate/

Request method: get

Request parameters: None

Request example: http://127.0.0.1:8000/app01/cate/

Interface format: json

Return data format:

[
    {
        'id': 1,
        'name': 'military'
    },
    {
        'id': 2,
        'name': 'Finance and Economics'
    }
]

3. Create a new vue page, request data and display it

<template>
    <div>
        <table class="t1">
            <tr>
                <td>number</td>
                <td>name</td>
                <td>operation</td>
            </tr>
            <tr v-for="cate in cate_list" :key="cate.id">
                <td>{{cate.id}}</td>
                <td>{{cate.name}}</td>
                <td>
                    <button>edit</button>
                    <button>delete</button>
                </td>
            </tr>
        </table>
    </div>
</template>
​
<script>
export default {
    data() {
        return {
            cate_list: []
        }
    },
    methods: {
        // Method of obtaining classification
        getCate() {
            // The logic of the classification method is executed here
            // Request data from background
            this.axios({ // axios default request is get, so you don't need to write method: get
                url: '/app01/cate/'
            }).then(res => {
                console.log(res.data)
                this.cate_list = res.data
            })
        }
    },
    created() {
        // Call before page loading completes
        this.getCate()
    }
}
</script>
​
<style scoped>
.t1 {
    width: 50%;
    margin: 30px auto;
}
</style>
​

 

2. Dynamic routing

Go to the details page

Jump the route and determine the information of the details to be obtained

1. Click the name, jump to the page and use router link

<router-link :to="{name: 'Detail', query: {'cate_id': cate.id}}">{{cate.name}}</router-link>

2. Operate on the details page

  • Get the classification id in the route

    <script>
    export default {
        data() {
            return {
                // 1. Get the classification id in the route
                cate_id: this.$route.query.cate_id
            }
        },
    }
    </script>
  • Through the obtained classification id, go to the background to query the corresponding data

    <script>
    export default {
        data() {
            return {
                // 1. Get the classification id in the route
                cate_id: this.$route.query.cate_id
            }
        },
        methods: {
            getDetail() {
                this.axios({
                    url: '/app01/detail/?cate_id=' + this.cate_id
                }).then(res => {
                    console.log(res.data)
                })
            }
        },
        created() {
            this.getDetail()
        }
    }
    </script>
  • Display data

    <template>
        <div>
            {{cate.id}} ------ {{cate.name}}
        </div>
    </template>
    ​
    <script>
    export default {
        data() {
            return {
                // 1. Get the classification id in the route
                cate_id: this.$route.query.cate_id,
                cate: {}
            }
        },
        methods: {
            getDetail() {
                this.axios({
                    url: '/app01/detail/?cate_id=' + this.cate_id
                }).then(res => {
                    console.log(res.data)
                    this.cate = res.data
                })
            }
        },
        created() {
            this.getDetail()
        }
    }
    </script>
    ​
    <style scoped>
    ​
    </style>
    ​

 

 

 

delete

 

 

1. Delete interface

class CateView(View):
    
    def delete(self, request):
        # 1. Get the parameters in the route
        cate_id = request.GET.get('cate_id')
        # 2. Get the object to delete
        # pk stands for primary key
        try:
            cate_obj = Cate.objects.get(pk=cate_id)
        except Cate.DoesNotExist:
            return JsonResponse({'msg': 'Get classification does not exist', 'code': 400})
        # 3. Delete
        cate_obj.delete()
        # 4. Delete succeeded, return message
        return JsonResponse({'msg': 'Deleted successfully', 'code': 200})

django can't get the exception thrown by data using get query, so it needs to use try except ion to catch the exception.

 

resolvent

try:
    cate_obj = Cate.objects.get(pk=cate_id)
# The exception is captured for the table queried by get.
except Cate.DoesNotExist:
    retrun JsonResponse({'msg': 'Classification does not exist', 'code': 400})

 

2. Interface document

Request address: http://127.0.0.1:8000/app01/cate/

Request method: delete

Request parameter: cat_ id

Request example: http://127.0.0.1:8000/app01/cate/?cate_id=1

Return data: json

Data format:

{
    'msg': 'Deleted successfully',
    'code': 200
}

3. In showcate On the Vue page, add a click event on the delete button

<template>
    <button @click="delCate(cate.id)">delete</button>
</template>
<script>
export default {
    methods: {
        // Delete classification
        // Delete classification
        delCate(cate_id) {
            console.log(cate_id)
            // Send request to deleted interface
            this.axios({
                url: '/app01/cate/?cate_id=' + cate_id,
                // The get request is sent by default, so you need to add the method as delete
                method: 'delete'
            }).then(res => {
                console.log(res.data)
            })
        },
    },
}
</script>

 

modify

 

1. Add click event for Edit button

<template>
    <button @click="toUpdate(cate.id)">edit</button>
</template>
​
<script>
export default {
    methods: {
        // To modify the page
        toUpdate(cate_id) {
            // Jump page
            this.$router.push({
                name: 'UpdateCate',
                query: {'cate_id': cate_id}
            })
        },
    },
}
</script>

2. Create a new updatecate Vue page

3. Is updatecate Vue add route

import Vue from 'vue'
import Router from 'vue-router'
import UpdateCate from '@/components/UpdateCate'
​
Vue.use(Router)
​
export default new Router({
  routes: [
    {
      path: '/update_cate',  // The path entered in the browser address bar
      name: 'UpdateCate',  // Use $router Parameters carried when pushing to jump to the page
      component: UpdateCate  // Jump to the vue page displayed after the path is approved
    }
      
  ]
})
​

4. Get the data of the object to be modified before the page is loaded (there should be a separate interface to get the data)

<script>
export default {
    data() {
        return {
            cate_id: this.$route.query.cate_id,
            cate: {},
            name: ''
        }
    },
    methods: {
        // Get classification details
        getDetail() {
            this.axios({
                url: '/app01/detail/?cate_id=' + this.cate_id
            }).then(res => {
                console.log(res.data)
                this.cate = res.data
                this.name = res.data.name
            })
        }
    },
    created() {
        // Get the details of the classification before the page is loaded, and call the getDetail() method
        this.getDetail()
    }
}
</script>

 

5. Show the acquired data and confirm what the original data is and what it should be modified into?

<template>
    <div>
        {{cate_id}}
        <div>
            Original data: {{cate.name}}
        </div>
        <div>Modified content: <input type="text" v-model="name"></div>
        <div><button>modify</button></div>
    </div>
</template>
​
<script>
export default {
    data() {
        return {
            cate_id: this.$route.query.cate_id,
            cate: {},
            name: ''
        }
    },
    methods: {
        // Get classification details
        getDetail() {
            this.axios({
                url: '/app01/detail/?cate_id=' + this.cate_id
            }).then(res => {
                console.log(res.data)
                this.cate = res.data
                this.name = res.data.name
            })
        }
    },
    created() {
        // Get the details of the classification before the page is loaded, and call the getDetail() method
        this.getDetail()
    }
}
</script>

6. Add a click event for modification and get the input content

<template>
    <div>
        <div><button @click="updateCate">modify</button></div>
    </div>
</template>
​
<script>
export default {
    methods: {
        // Modify classification
        updateCate() {
            console.log(this.name)
        },
    },
}
</script>
​
<style scoped>
​
</style>
​

7. Interface for modifying data

class CateView(View):
    
    def put(self, request):
       
        # 2. Get the submitted modified data
        print(request.body)
        name_str = (request.body).decode()
        # Convert ACCESS Dictionary to json
        name_dict = json.loads(name_str)
        cate_id = name_dict.get('cate_id')
        name = name_dict.get('name')
        # 3. Query the object to be modified through the id of the object
        cate_obj = Cate.objects.get(pk=cate_id)
        # 4. Re assign values to the attributes in the query object and save them
        cate_obj.name = name
        cate_obj.save()
        # 5. If the modification is successful, a message is returned
        return JsonResponse({'msg': 'Modified successfully', 'code': 200})

8. Modified interface document

Request address: http://127.0.0.1:8000/app01/cate/

Request method: put

Request parameters:

fieldtypeRequiredexplain
cate_idinttrueObject id to modify
namestringtrueModified content

Return data:

{
    'msg': 'Modified successfully',
    'code': 200
}

9. Complete modification function

<template>
    <div>
        {{cate_id}}
        <div>
            Original data: {{cate.name}}
        </div>
        <div>Modified content: <input type="text" v-model="name"></div>
        <div><button @click="updateCate">modify</button></div>
    </div>
</template>
​
<script>
export default {
    data() {
        return {
            cate_id: this.$route.query.cate_id,
            cate: {},
            name: ''
        }
    },
    methods: {
        // Modify classification
        updateCate() {
            console.log(this.name)
            this.axios({
                url: '/app01/cate/',
                method: 'put',
                data: {'cate_id': this.cate_id, 'name': this.name}
            }).then(res => {
                // Print the returned results on the console
                console.log(res.data)
            })
        },
        // Get classification details
        getDetail() {
            this.axios({
                url: '/app01/detail/?cate_id=' + this.cate_id
            }).then(res => {
                console.log(res.data)
                this.cate = res.data
                this.name = res.data.name
            })
        }
    },
    created() {
        // Get the details of the classification before the page is loaded, and call the getDetail() method
        this.getDetail()
    }
}
</script>
​
<style scoped>
​
</style>
​

 

 

 

Added by Nirvana on Tue, 01 Feb 2022 11:30:09 +0200