django rest framework 与 Vue 整合遇到的坑

前提是已经有了Django项目与前端Vue打包好的dist文件

好,开始整合!!!

当然还是先设置Django的setting.py

1设置模板路径

2 设置静态文件路径

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['appfront/dist'],#****设置它****
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]


######静态文件路径#####
STATIC_URL = '/static/'  #注意是static
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'appfront/dist/static/'),)

然后设置路由了

由于drf使用路由注册,所以不能跟往常那样匹配路由设置

router = DefaultRouter()
router.register(r'backend/video_list', VideosViewset, base_name='video_list')
router.register('backend/create_lunbo', LunboViewset, base_name='create_lunbo')

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name='index.html')),#####千万记住,别写东西,要不然只走后端,不走前端路由
    re_path(r'create_lunbo/media/images/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}),
]
urlpatterns += router.urls

注意是使用

urlpatterns += router.urls

来是路由生效。  前端的index.html是通过 

TemplateView.as_view(template_name='index.html')

 加载静态index文件,好了,这样就实现相结合了。

posted on 2019-04-09 11:00  天下无槛,不服就干  阅读(321)  评论(0编辑  收藏  举报

导航