I\'ve recently started on some social media web site using Django. Im using the default django template engine to fill my pages. But at this moment, I want to a
This is how I integrate Vue with a Django project:
The first approach is building separate Django and Vue apps. Django will be responsible for serving the API built using Django REST framework and Vue will consume these APIs using the Axios client or the browser's fetch API. You'll need to have two servers, both in development and production, one for Django(REST API) and the other for Vue (to serve static files).
The second approach is different the frontend and backend apps will be coupled. Basically you'll use Django to both serve the Vue frontend and to expose the REST API. So you'll need to integrate Vue and Webpack with Django, these are the steps that you can follow to do that
First generate your Django project then inside this project directory generate your Vue application using the Vue CLI
For Django project install django-webpack-loader
with pip:
pip install django-webpack-loader
Next add the app to installed apps and configure it in settings.py by adding the following object
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': '',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
}
}
Then add a Django template that will be used to mount the Vue application and will be served by Django
{ % load render_bundle from webpack_loader % }
Django + Vue
This is where Vue will be mounted
{ % render_bundle 'app' % }
Then add an URL in urls.py to serve this template
from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
url(r'^', TemplateView.as_view(template_name="main.html")),
]
If you start both the Django and Vue servers at this point you'll get a Django error saying the webpack-stats.json doesn't exist. So next you need to make your Vue application able to generate the stats file.
Go ahead and navigate inside your Vue app then install webpack-bundle-tracker
npm install webpack-bundle-tracker --save
Go to build/webpack.base.conf.js
then add
let BundleTracker = require('webpack-bundle-tracker')
module.exports = {
// ...
plugins: [
new BundleTracker({filename: '../webpack-stats.json'}),
],
}
This add the BundleTracker plugin to Webpack and tell it to generate the webpack-stats.json
file in the parent folder where Django files live.
Now if you re-run your Vue server the webpack-stats.json will be generated and Django will be able to consume it to find information about the Webpack bundles generated by Vue dev server.
You can find more information from this tutorial.