Build A Single Page App Using Django & Vue.js

    In the Django Tutorial For Beginners, we went through the basics of the Python Django framework. And in this article, we will talk about how to make Django and Vue.js, a JS frontend framework, to work together. You can find a complete example project on my GitHub: https://github.com/ericnanhu/Django_Vue

    Create A New Django Project

    Let’s start by creating a new Django project like we talked about in this tutorial: Django Tutorial #1: Setup the Project

    Install Vue CLI

    In order to set up a Vue frontend environment, we need to install Vue CLI first. The CLI is a globally installed npm package and provides the vue command in your terminal.

    npm install -g @vue/cli

    You can check you have the right version with this command:

    vue --version

    Create Vue Frontend

    After installing Vue CLI, use the following command to create a frontend environment:

    vue create frontend

    This command will create a new directory named frontend, and install the Vue environment in it.

    Then you will be prompted to select the presets, and usually, the default setting is sufficient.

    $ Vue CLI v4.3.1
      ? Please pick a preset: Manually select features
      ? Check the features needed for your project: Babel, Router, Vuex
      ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
      ? Where do you prefer placing config for Babel, ESLint, etc.? In package.json
      ? Save this as a preset for future projects? (y/N) N
    
      ### installation magic happens...
    
    ????  Successfully created project frontend.
    ????  Get started with the following commands:
    $ cd frontend
    $ npm run serve

    Install Vue Webpack Bundle Tracker

    Now we have both frontend and backend environments installed. Next thing we need to do is to make sure that the two environments can talk to each other. To do that, we install the Webpack Bundle Tracker on the Vue.js side, and Webpack Load on the Djnago side.

    First go to the frontend directory we just created:

    cd frontend

    Then install the webpack-bundle-tracker:

    npm install webpack-bundle-tracker@0.4.3

    You need to specify the version of the webpack-bundle-tracker you are installing. If you don’t, npm will get the latest alpha version, and it will not work the same. Next, we need to create a configuration file for Vue.js in the frontend directory.

    Vue Configuration File

    vue.config.js

    const BundleTracker = require("webpack-bundle-tracker");
    
    module.exports = {
      publicPath: "http://127.0.0.1:8080/",
      outputDir: "./dist/",
    
      chainWebpack: (config) => {
        config
          .plugin("BundleTracker")
          .use(BundleTracker, [{ filename: "./webpack-stats.json" }]);
    
        config.output.filename("bundle.js");
    
        config.optimization.splitChunks(false);
    
        config.resolve.alias.set("__STATIC__", "static");
    
        config.devServer
          // the first 3 lines of the following code have been added to the configuration
          .public("http://127.0.0.1:8080")
          .host("127.0.0.1")
          .port(8080)
          .hotOnly(true)
          .watchOptions({ poll: 1000 })
          .https(false)
          .disableHostCheck(true)
          .headers({ "Access-Control-Allow-Origin": ["*"] });
      }
    
      // uncomment before executing 'npm run build'
      // css: {
      //     extract: {
      //       filename: 'bundle.css',
      //       chunkFilename: 'bundle.css',
      //     },
      // }
    };

    Install Django Webpack Loader

    Now, go back to the root directory of our project, and install the django-webpack-loader. Make sure the virtual environment has been activated.

    pip install django-webpack-loader

    Then, add webpack-loader into Django’s INSTALLED_APPS list in settings.py file, and make a few changes to it.

    Django Settings File

    INSTALLED_APPS = [
             ...
        'webpack_loader',
    ]
    
        .
        .
        .
    TEMPLATES = [
        {               ...
    
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
                        ...
        },
    ]
        .
        .
        .
    
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, "assets"),
        os.path.join(BASE_DIR, "frontend/dist"),
    ]
    
    WEBPACK_LOADER = {
        'DEFAULT': {
            'BUNDLE_DIR_NAME': 'dist/',
            'STATS_FILE': os.path.join(BASE_DIR, 'frontend', 'webpack-stats.json')
        }
    }
    

    Create Our First App

    Now, to test if the two environments can work with each other, we create a core app in out Django project:

    python manage.py startapp core

    View

    core/views.py

    def vue_app(request):
        return render(request, 'vue.html')

    Template

    templates/vue.html

    {% load render_bundle from webpack_loader %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <div id="app"></div>
    {% render_bundle 'app' %}
    </body>
    </html>

    URL

    Django_Vue/urls.py

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('vue-app/', views.vue_app),
    ]

    Once we have made these changes, we can serve both frontend and backend apps. Go to frontend directory:

    cd frontend
    npm run serve

    Open another terminal, and serve the backend. Make sure the virtual environment is activated when you do this.

    python manage.py runserver

    Now, open the browser and go to http://127.0.0.1:8000/vue-app. This is what you should get if Vue and Django can work with each other:

    Leave a Reply

    Your email address will not be published. Required fields are marked *