由於現在前端使用的三大框架配合webpack可以實現快速打包,爲部署到服務端提供了非常大的便利,那麼在前端打包後,應該做些什麼可以部署到django的後臺中呢?
1.打包後文件包dist
進入到 dist文件包會發現是這個樣子的:
2.在django項目中創建前端文件包(靜態資源包,我習慣起名爲frontend) 然後把dist文件包中的static文件包和index.html拷貝過去,接着把static文件包中的所有文件和index文件都剪切到上一層目錄(都在frontend中),由於我們Vue構建的是單頁應用所以一般只有一個html。做完這些後吧static這個空文件包刪掉就行了。這樣就形成了django後臺的靜態文件包。
3.在settings中配置靜態文件以及模板 這裏的index.html就相當於是template中的html文件,爲了方便就把靜態資源和這個模板文件整合在一個文件包中。
首先是template配置:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'frontend')], '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_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "frontend"), ] 4.創建一個app,並且在views中寫一個index路由函數,並且在url中配置首頁 #加載靜態界面index首頁 def index(request): request.META["CSRF_COOKIE_USED"] = True return render(request,'index.html') request.META["CSRF_COOKIE_USED"] = True這句可以對vue單頁應用進行csrf_token設置,方便進行csrf防禦
urlpatterns = [ url(r'^baseapi/', include("baseapp.urls")), url(r'^.*?$',views.index,name="index"), ] url(r'^.*?$',views.index,name="index")設置後,啓動django,訪問8000端口就可以加載到前端的路由了
或者,直接在url中加入:
from django.views.generic import TemplateView
path('', TemplateView.as_view(template_name='index.html'), name='index'),
--------------------- 原文:https://blog.csdn.net/qq_41000891/article/details/82961680