1.安装pymysql,mysqlclient,创建项目django-admin startproject django3
2.在Mysql中创建一个数据库叫django3db,打开项目,修改一下数据库配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django3db',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
3.创建一个app,python manage.py startapp myapp
在settings.py中添加一下新创建的app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]
4.在myapp文件夹下的models.py中粘帖如下代码
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.更新一下数据库
python manage.py makemigrations
python manage.py migrate
6.安装rest framework,己安装的跳过安装,但要在settings.py中加一下
INSTALLED_APPS = [ ... 'rest_framework', ]
7.urls.py中添加,记得引用一下include
urlpatterns = [ ... url(r'^api-auth/', include('rest_framework.urls')) ]
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.在myapp下创建文件serializers.py,粘帖如下代码:
from rest_framework import serializers
from myapp.models import Person
class PersonSerializer(serializers.ModelSerializer):
# ModelSerializer和Django中ModelForm功能相似
# Serializer和Django中Form功能相似
class Meta:
model = Person
# 和"__all__"等价
fields = ('id', 'name', 'age')
10.在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.在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.运行项目,会看到这样的图
13.点一下那个http://127.0.0.1:8000/persons,会看到如下画面,有一个中括号[],这是因为数据表为空,所以没数据
14. 上图下方有两个框,输入姓名和年龄,点击POST,你会看到下图,有DELETE和PUT,可以试试能不能用。
15.还要解决一下跨域问题
pip install django-cors-middleware
在settings.py的app那边添加
'corsheaders',
在settings.py的Middle Ware那边的最上方,必须是最上方添加
'corsheaders.middleware.CorsMiddleware',
继续settings.py,添加以下
CORS_ORIGIN_ALLOW_ALL = True
16.最后是vue.js,完成的组件代码如下
添加
{{ scope.row.id}}
{{ scope.row.age}}
{{ scope.row.name}}
修改
删除