current position:Home>Django + Vue realizes the operation of adding, deleting, modifying and querying
Django + Vue realizes the operation of adding, deleting, modifying and querying
2022-01-26 23:01:40 【Classmate an downstairs】
One 、 Static routing
urlpatterns attribute
urlpatterns Is a global variable in the routing file , The mapping relationship used to store routing and view functions
User initiated requests URL
Will first enter this... Under the main control directory urls.py
Find a match in the file
- First find
urls.py
Under theurlpatterns
Global variables , This is a list of routing rule instances . - Define in order , Route matching .
- Stop matching when the first match is found , Execute the matching view function .
- Ergodic complete , No match found ,
django
Do exception handling
among urlpatterns
Each routing mapping rule in can be defined by path
or re_path
Construct
Be careful :Django
Routing of does not consider HTTP
Request mode , Only according to URL Routing ; namely , as long as URL
identical , No matter what POST
、GET
And so on, which request mode points to the same operation function
Two 、 The outline
preparation : newly build Django project , The configuration file , route , Set up cross domain , newly build Vue project , Configure the routing , Design database tables (Cate id and name Field )、 Generate the migration file and execute the migration file
3、 ... and 、 increase
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 , Return message , Incomplete data
if not name:
return JsonResponse({
'msg': ' Incomplete data ', 'code': 400}, json_dumps_params={
'ensure_ascii': False})
# If you get the data , add to
Cate.objects.create(name=name)
return JsonResponse({
'msg': ' Add success ', 'code': 200}, json_dumps_params={
'ensure_ascii': False})
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 the data :
# request was aborted , Prompt when data is empty
{
'msg': ' Incomplete data ',
'code': 400
}
# The request is successful
{
'msg': ' Add success ',
'code': 200
}
Configure global axios
stay src Under the folder main.js among , To configure
2、 stay src Under the components Under the new AddCate.vue page
<template>
<form action="">
<p> Category name : <input type="text" v-model="name"></p>
<p><button> add to </button></p>
</form>
</template>
<script>
export default {
data() {
return {
name: ''
}
}
</script>
Four 、 Display data
1、 Show 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、 Return data to json returns
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 : nothing
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、 newly build vue page , Request data , And show
<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: {
// How to get the classification
getCate() {
// Here, the logic of the method of classification
// Request data from the background
this.axios({ // axios The default request is get, So you don't have 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 route , Information that determines the details to be obtained
1、 Click on the name , Jump to the page , 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 in the route id
<script> export default { data() { return { // 1、 Get the classification in the route id 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 in the route id 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 in the route id 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、 ... and 、 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、 Gets the object to delete
# pk Represents the 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 successful , Return message
return JsonResponse({
'msg': ' Delete successful ', 'code': 200})
django Use get Inquire about Exception thrown when data cannot be obtained , Need to use try except Exception capture .
- resolvent
try:
cate_obj = Cate.objects.get(pk=cate_id)
# get Which table to query , Which table will be exception captured .
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 parameters : cate_id
Request example : http://127.0.0.1:8000/app01/cate/?cate_id=1
Return the data :json
data format :
{
'msg': ' Delete successful ',
'code': 200
}
3、 stay ShowCate.vue In the middle of the page , Add click event on delete button
<template>
<button @click="delCate(cate.id)"> Delete </button>
</template>
<script>
export default {
methods: {
// Delete category
// Delete category
delCate(cate_id) {
console.log(cate_id)
// Send request to deleted interface
this.axios({
url: '/app01/cate/?cate_id=' + cate_id,
// Default send get request , So you need to add method by delete This request method
method: 'delete'
}).then(res => {
console.log(res.data)
})
},
},
}
</script>
6、 ... and 、 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 to the page
this.$router.push({
name: 'UpdateCate',
query: {'cate_id': cate_id}
})
},
},
}
</script>
2、 newly build UpdateCate.vue page
3、 by 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.push When you jump to a page , Parameters with
component: UpdateCate // Jump to the page approved by the path , As suggested by the Of vue page
}
]
})
4、 Get the data of the object to be modified before the page is loaded ( There should be a separate interface to obtain 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 , call getDetail() This method
this.getDetail()
}
}
</script>
5、 Display the obtained data , Confirm what the original data is , What to change to ?
<template>
<div>
{
{cate_id}}
<div>
The original data : {
{cate.name}}
</div>
<div> Modify the 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 , call getDetail() This method
this.getDetail()
}
}
</script>
6、 Add click event for modification , Get the input
<template>
<div>
<div><button @click="updateCate"> modify </button></div>
</div>
</template>
<script>
export default {
methods: {
// Modify the classification
updateCate() {
console.log(this.name)
},
},
}
</script>
<style scoped>
</style>
7、 Interface to modify data
class CateView(View):
def put(self, request):
# 2、 Get the submitted modified data
print(request.body)
name_str = (request.body).decode()
# Use json Turn the acquired content into a dictionary
name_dict = json.loads(name_str)
cate_id = name_dict.get('cate_id')
name = name_dict.get('name')
# 3、 Of the object of communication id Query the object to modify
cate_obj = Cate.objects.get(pk=cate_id)
# 4、 Re assign values to the attributes in the query object , And save
cate_obj.name = name
cate_obj.save()
# 5、 Modification successful , Return message
return JsonResponse({
'msg': ' Modification successful ', '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 | The object to be modified id |
name | string | true | Revised content |
Return the data :
{
'msg': ' Modification successful ',
'code': 200
}
9、 Complete the modification function
<template>
<div>
{
{cate_id}}
<div>
The original data : {
{cate.name}}
</div>
<div> Modify the 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 the 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 , call getDetail() This method
this.getDetail()
}
}
</script>
Dynamic routing parameter transmission
sometimes , The route we set is not invariable , Such as : We need to jump to the details , You need to view all goods under a category through a category , In fact, such a route should correspond to a view function , To show the content of the page , So how to design such a route , It involves dynamic routing and routing parameters
1、 By classification id Get classification details
**2、 Dynamic routing configuration **
Routes are matched by angle brackets , Use int as well as str The built-in converter converts the value of the corresponding part of the connection ; And pass the matching result to the parameter position corresponding to the view function ;
visit : http://127.0.0.1:8000/app01/detail/1/
among 1 Will serve as a cate_id The parameters of are received .
- Other built-in Path converter , Our routing parameters can be specified as the specified type
''' str: Matches except for the path separator (`/`) A non - empty string , This is the default form int: Matching positive integer , contain 0 slug: Match the letter 、 Numbers and bars 、 String of underscores uuid: Match formatted uuid, Such as 075194d3-6885-417e-a8a8-6c931e272f00 path: Match any non empty string , Contains the path separator '''
Dynamic routing participation GET The similarities and differences of Chuan Shen
- Dynamic routing parameter transmission , Parameters need to participate in route matching , Get parameters in route matching
- GET Parameters , The parameter part does not need to participate in route matching , Get parameters in view
3、 Routing distribution
The concept of routing distribution
Our routing is written in the main directory of the project urls.py
In file , But if app
There are a lot of words , So many routes are written together , It's obviously a very inconvenient thing to manage
In fact, in the previous exercise , We use routing distribution , Each child app
Have their own independent urls.py
Route mapping file , The master routing file only needs to use include
Function importer app
Just download the routing file , This is known as route distribution
include Routing distribution implementation
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('app01/',include("app01.urls")) # Use include Implement routing distribution , Find the child app The routing file under
]
Routing distribution brings us many benefits , Can let us in multiple app
More convenient and effective management of each route in the project
And it can also let our users see... In the browser when accessing URL
Address more Feast for the eyes
Cross domain
Fore and aft end separation , Homology strategy problem
Different ports
python Package management tools
pip
pip install Package name
pip show Package name
# Check whether a package is installed
cnpm install --save Package name
node.js Package management tools :cnpm
pip install django-cors-headers
install django Background cross domain package
Configure cross domain
# settings.py
INSTALLED_APPS = [
'corsheaders',
]
# middleware
MIDDLEWARE = [
# The third line
'corsheaders.middleware.CorsMiddleware',
# Note the fifth line
]
# Allow all source access
CORS_ALLOW_ALL_ORIGINS = True
django An admin command
# The command to create a project
django-admin startproject projectname
# establish app
Entry project : cd projectname
python manage.py startapp appname
# Generate migration file
python manage.py makemigrations
# Perform migration file
python manage.py migrate
Distribution has brought us many benefits , Can let us in multiple app
More convenient and effective management of each route in the project
And it can also let our users see... In the browser when accessing URL
Address more Feast for the eyes
Cross domain
Fore and aft end separation , Homology strategy problem
Different ports
python Package management tools
pip
pip install Package name
pip show Package name
# Check whether a package is installed
cnpm install --save Package name
node.js Package management tools :cnpm
pip install django-cors-headers
install django Background cross domain package
Configure cross domain
# settings.py
INSTALLED_APPS = [
'corsheaders',
]
# middleware
MIDDLEWARE = [
# The third line
'corsheaders.middleware.CorsMiddleware',
# Note the fifth line
]
# Allow all source access
CORS_ALLOW_ALL_ORIGINS = True
django An admin command
# The command to create a project
django-admin startproject projectname
# establish app
Entry project : cd projectname
python manage.py startapp appname
# Generate migration file
python manage.py makemigrations
# Perform migration file
python manage.py migrate
Good things have happened in the last three days , Focus on me and study together IT!!! Thank you for your support !
copyright notice
author[Classmate an downstairs],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262301172989.html
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- Anaconda can't open it
guess what you like
-
I don't know how to start this
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
Suzhou computer research
-
After installing SSL Certificate in Windows + tomcat, the domain name request is not successful. Please answer!!
-
Implementation time output and greetings of jQuery instance
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
Random recommended
- Springboot implements excel import and export, which is easy to use, and poi can be thrown away
- The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
- Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
- C + + recursive knapsack problem
- The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
- PostgreSQL statement query
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- If you want an embedded database (H2, hsql or Derby), please put it on the classpath
- When using stm32g070 Hal library, if you want to write to flash, you must perform an erase. If you don't let it, you can't write continuously.
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Fresh students are about to graduate. Do you choose Java development or big data?
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Vectorization of deep learning formula
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- For someone, delete return 1 and return 0
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Webpack packaging optimization solution
- 5. Operation element
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of springboot default package scanning mechanism and @ componentscan specified scanning path
- How to solve the run-time exception of test times
- Detailed explanation of k8s management tool kubectl
- Android system view memory command