django_vue (django部分搭建及操作)

鲍健柏
2023-12-01

参考django3新建第一个项目(详情django3新建项目可查看这个目录)

1.安装python3

pip install django

pip install djangorestframework (django序列化数据)

pip install django-cors-headers (django 跨域)

2. django-admin startproject vue-django (建项目)

3.python manage.py startapp lyb (建模块)

4.settings.py 文件中INSTALLED_APPS 添加 ‘lyb’  (把新建的模块 到 安装的app中注册一下)

5.models文件,添加

class Lyb(moddels.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    content = models.TextField()
    posttime = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "d_lyb"

6.python manage.py migrate(创建数据库)

7.序列化数据(restframework) 可以参照官方文档

新建文件 serializers.py

from rest_framework import serializers
from .models import Lyb

# 序列化器
class LybSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Lyb  # 序列化的模型,上面导入
        # fields = ['url', 'username', 'email', 'groups']
        fields = "__all__"

7.1 添加视图文件 view.py

from django.shortcuts import render
from rest_framework import viewsets
from .models import Lyb  # 导入模板
from serializers import LybSerializer

class LybViewSet(viewsets.ModelViewSet):
    queryset = Lyb.objects.all().order_by('-posttime')  # 按照 posttime 排序
    serializer_class = LybSerializer # 使用序列化器

7.2 路由 urls.py

from django.contrib import admin
from django.urls import path, include
from rest_framework import routers #导入 routers
from lyb.views import LybViewSet  # 导入视图

# view 注册到路由里
router = routers.DefaultRouter()
router.register(r'lyb', LybViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include(router.urls)),
]

此时,api/lyb就是提供序列化结果

7.3 settings.py 文件中INSTALLED_APPS 添加 rest_framwork

8.运行 python manage.py runserver

9.跨域设置

settings文件中添加:

INSTALLED_APPS = [ ... 'corsheaders', ... ]

MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # 放最前面 ... ]

CORS_ORIGIN_ALLOW_ALL = True

 类似资料: