1, Static routing
urlpatterns attribute
urlpatterns is a global variable in the routing file, which is used to store the mapping relationship between routing and view functions
The request URL initiated by the user will first enter the URLs under the main control directory Py file
- First find URLs The urlpatterns global variable under py, which is the list data of a routing rule instance.
- Route matching is performed according to the order of definition.
- When the first match is found, stop matching and execute the matched view function.
- The traversal is complete and no match is found. django handles the exception
Each route mapping rule in urlpatterns can be defined by path or re_path
Note: the route of Django does not consider the HTTP request mode, and only routes according to the URL; That is, as long as the URL is the same, no matter which request method such as POST or GET points to the same operation function
2, Outline
Preparations: create a new Django project, configure files and routes, set cross domain, create a new Vue project, configure routes, design database tables (Cate id and name fields), generate migration files and execute migration files
3, Increase
-
Add classification interface (add)
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})
-
Add route
from django.urls import path from . import views urlpatterns = [ path('cate/', views.CateView.as_view()), # Category addition, deletion, modification and query ]
- Classification interface document
Request address: http://127.0.0.1:8000/app01/cate/
Request method: post
Request parameters:
field | type | Required |
---|---|---|
name | string | true |
Return data:
# Prompt when the request fails and the data is empty { 'msg': 'Incomplete data', 'code': 400 } # Request succeeded { 'msg': 'Added successfully', 'code': 200 }
-
Under vue, create addcate vue page to realize the function of page form
Configure global axios
Under src folder, main JS
2. Create addcate. Under components under src Vue page
<template> <form action=""> <p>Classification Name: <input type="text" v-model="name"></p> <p><button>add to</button></p> </form> </template> <script> export default { data() { return { name: '' } } </script>
4, 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>
5, 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>
6, Modification
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>
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 it more convenient and effective for us to manage 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 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 install django background cross domain package
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
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 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 install django background cross domain package
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
Good things have happened in the last three days. Pay attention to me and learn IT together!!! Thank you for your support!