1. Install pymysql, mysqlclient, creating a project django-admin startproject django3
2. Create a Mysql database called django3db, open the project, modify the database configuration
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django3db',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
3. Create a app, python manage.py startapp myapp
In settings.py add it in the newly created app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]
4. The paste following code models.py myapp folder in
class Person(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
age = models.IntegerField()
def __str__(self):
# 在Python3中使用 def __str__(self):
return self.name
5. Update about the database
python manage.py makemigrations
python manage.py migrate
6. Installation rest framework, fitted skipping installation, but was added in about settings.py
INSTALLED_APPS = [ ... 'rest_framework', ]
Add 7.urls.py in, remember to cite include
urlpatterns = [ ... url(r'^api-auth/', include('rest_framework.urls')) ]
Add about in 8.settings.py
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny', #任何人都可以访问
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
),
}
9. serializers.py create a file in myapp, paste the following code:
Import rest_framework serializers from
from myapp.models Import the Person
class PersonSerializer (serializers.ModelSerializer):
# ModelSerializer and functionally similar in Django ModelForm
# Serializer and functionally similar in Django Form
class Meta -:
Model the Person =
# and "__all__" equivalent
fields = ( 'id', 'name', 'age')
10. The following code in the paste in the app views.py:
from rest_framework import viewsets, authentication, mixins
from rest_framework.permissions import IsAuthenticated
from myapp.models import Person
from myapp.serializers import PersonSerializer
class PersonViewSet(viewsets.ModelViewSet):
queryset = Person.objects.all()
serializer_class = PersonSerializer
11. Add the urls.py
from rest_framework import routers
from myapp.views import PersonViewSet
router = routers.DefaultRouter()
router.register(r'persons', PersonViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
12. Run the project, see this chart
13. Tap the http://127.0.0.1:8000/persons, will see the following screen, there is a bracket [] This is because the data table is empty, so no data
Figure 14. There are two on the bottom box, enter the name and age, click POST, you will see the following figure, there are DELETE and PUT, you can see if you can use.
15. Finally vue.js, following assembly code completion
<template>
<div>
<p style="text-align: left;">
<el-button type="primary" @click="dialogFormAdd = true">添加</el-button>
</p>
<el-table :data="tableData" stripe border style="width:100%" highlight-current-row>
<el-table-column type="selection" width="55">
</el-table-column>
<el-table-column prop="id" label="ID" align="center" min-width="120">
<template slot-scope="scope">
<span>{{ scope.row.id}}</span>
</template>
</el-table-column>
<el-table-column prop="age" label="年龄" align="center" min-width="100">
<template slot-scope="scope">
<span>{{ scope.row.age}}</span>
</template>
</el-table-column>
<el-table-column prop="name" label="姓名" align="center" min-width="120">
<template slot-scope="scope">
<span>{{ scope.row.name}}</span>
</template>
</el-table-column>
<el-table-column label="操作" align="center" min-width="100">
<template slot-scope="scope">
<el-button type="info" @click="toEdit(scope)">修改</el-button>
<el-button type="info" @click="deleteUser(scope)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog title="修改人员" :visible.sync="dialogFormEdit">
<el-form :model="person">
<el-form-item label="编号" >
<el-input v-model="person.id" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="年龄" >
<el-input v-model="person.age" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="姓名" >
<el-input v-model="person.name" auto-complete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormEdit = false">取 消</el-button>
<el-button type="primary" @click="edit(person)">确 定</el-button>
</div>
</el-dialog>
<el-dialog title="添加人员" :visible.sync="dialogFormAdd">
<el-form :model="person">
<el-form-item label="编号" >
<el-input v-model="person.id" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="年龄" >
<el-input v-model="person.age" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="姓名" >
<el-input v-model="person.name" auto-complete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormAdd = false">取 消</el-button>
<el-button type="primary" @click="add(person)">确 定</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
export default {
name: 'PersonTableDjango',
data () {
return {
tableData: [],
dialogFormEdit: false,
dialogFormAdd: false,
person: {
id: '',
age: '',
name: ''
}
}
},
methods: {
init () {
var self = this
this.$axios.get('http://127.0.0.1:8000/persons/')
.then(function (res) {
// console.log(res.data)
self.tableData = res.data
})
.catch(function (err) {
console.log(err)
})
},
add (person) {
let params = new URLSearchParams()
params.append('name', person.name)
params.append('age', person.age)
this.$axios.post('http://127.0.0.1:8000/persons/', params).then(res => {
// if (res.data.success === true) {
this.$message.success('添加成功')
this.dialogFormAdd = false
this.init()
// this.checkTable()
// } else {
// this.$message.warning(res.data.msg)
// }
})
.catch(function (error) {
console.log(error)
})
},
edit (person) {
let params = new URLSearchParams()
// params.append('id', person.id)
params.append('name', person.name)
params.append('age', person.age)
this.$axios.put('http://127.0.0.1:8000/persons/' + person.id + '/', params).then(res => {
// if (res.data.success === true) {
this.$message.success('修改成功')
this.dialogFormEdit = false
this.init()
// this.checkTable()
// } else {
// this.$message.warning(res.data.msg)
// }
})
.catch(function (error) {
console.log(error)
})
},
toEdit (scope) {
this.person.id = scope.row.id
this.person.age = scope.row.age
this.person.name = scope.row.name
this.dialogFormEdit = true
},
deleteUser (scope) {
if (!scope.row.id) {
this.tableData.splice(scope.$index, 1)
} else {
this.$confirm('确认是否删除', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
center: true
})
.then(() => {
console.log(scope.row.id)
this.$axios.delete('http://127.0.0.1:8000/persons/' + scope.row.id + '/').then(res => {
// if (res.data.success === true) {
this.$message.success('删除成功')
this.init()
// this.checkTable()
// } else {
// this.$message.warning(res.data.msg)
// }
})
.catch(function (error) {
console.log(error)
})
})
.catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
})
})
}
}
},
mounted: function () {
this.init()
}
}
/* eslint-disable no-new */
</script>
<style scoped>
</style>