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() # Use json to convert the obtained content into a dictionary 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:
field | type | Required | explain |
---|---|---|---|
cate_id | int | true | Object id to modify |
name | string | true | Modified 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>
Dynamic routing parameters
Sometimes, the route we set is not invariable. For example, we need to jump to the details and view all the goods under a category through a category. In fact, such a route should correspond to a view function to display the page content. How to design such a route involves dynamic routing and route transmission parameters
1. Obtain the classification details through the classification id
**2. Dynamic routing configuration**
The route is matched by angle brackets, and the value of the corresponding part of the connection is converted by int and str built-in converters; And transfer the matching result to the parameter position corresponding to the view function;
visit: http://127.0.0.1:8000/app01/detail/1/
Where 1 will be used as cat_ The parameter of ID is received.
- Other built-in Path converters can specify our routing parameters to the specified type
''' str: Match except path separator(`/`)Non empty string, which is the default form int: Match positive integer, including 0 slug: Matches a string of letters, numbers, horizontal bars, and underscores uuid: Match formatted uuid,Such as 075194 d3-6885-417e-a8a8-6c931e272f00 path: Matches any non empty string, including the path separator '''
Similarities and differences between dynamic routing and GET parameters
- Parameters need to be involved in route matching, and parameters are obtained in route matching
- GET parameter. The parameter part does not need to participate in route matching. GET the parameter in the view
3. Routing distribution
Concept of routing distribution
Our routing is written in URLs. Com under the main directory of the project Py file, but if there are many app s, so many routes are written together, which is obviously a very inconvenient thing to manage
In fact, in the previous exercise, we used routing distribution, and each sub app has its own independent URLs Py route mapping file. In the master route file, you only need to use the include function to import the route file under the sub app, which is route distribution
Implementation of include routing distribution
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('app01/',include("app01.urls")) # Use include to realize route distribution and find the route file under the sub app ]
Routing distribution brings us many benefits, which can make us more convenient and effective in managing each route in multiple app projects
And it can also make our users see the URL address in the browser when visiting, which is more pleasing to the eye
Cross domain
Front and back end separation, homology strategy problem
Different ports
python's package management tool {pip
pip install package name
pip show package name # check whether a package is installed
cnpm install --save package name: node JS package management tool: cnpm
PIP install django CORS headers
Configure cross domain
# settings.py INSTALLED_APPS = [ 'corsheaders', ] # middleware MIDDLEWARE = [ # Third line 'corsheaders.middleware.CorsMiddleware', # Note the fifth line ] # Allow all source access CORS_ALLOW_ALL_ORIGINS = True
django administrative command
# Commands for creating projects django-admin startproject projectname # Create app Enter project: cd projectname python manage.py startapp appname # Generate migration file python manage.py makemigrations # Execute migration file python manage.py migrate