Using VueJS alongside Django
Thomas Kainrad
Posted on September 2, 2020
Introduction
I am the creator of https://keycombiner.com. It is a web application to organize the keyboard shortcuts you use, get better at using them, and to learn new ones. The whole thing is quite challenging because the project's scope is significant, and I am doing it alone in my spare time while working full time. So I have to be very efficient. Fortunately, I am using Django with its batteries-included approach.
I use all kinds of Django features that speed up my development, and I wouldn't want to miss its template engine. Therefore, using Django only in the backend and building a JavaScript SPA for the frontend is not an option for me.
However, even the most avid backend developer has to admit that some things warrant a client-side implementation. Small user actions should not require page reloads. Also, some parts of the web application I am building require rather sophisticated user interaction.
Traditionally, one would mix Django with some jQuery to achieve the desired behavior. But there are newer JavaScript technologies now: React and Vue.
Since our goal is to find a framework that we can use alongside Django without rethinking everything, we will go for Vue as the more lightweight alternative.
In this post, I will show that you can start to use Vue alongside Django's template language with minimal effort.
Installation and Setup
One of the reasons to use Vue is its excellent documentation. It includes many examples, has a decent search, and a reasonably clear table of contents.
This post aims to show that you can start to use Vue with your Django projects immediately without any sophisticated setup that will take hours to complete. Therefore, we will use the simplest method to use Vue.js: Including it via a <script>
tag.
<!-- development version, includes helpful console warnings -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
That is it, we are now ready to create our first Vue.js instance:
<div id="app">
{{ message }}
</div>
var app = new Vue({
delimiters: ["[[", "]]"],
el: '#app',
data: {
message: 'Hello Vue!'
}
})
This example is taken from the official Getting Started Guide. However, there is one addition. Per default, Django and Vue use the same template tags. Hence, we need to set the Vue delimiters explicitly to avoid conflicts with Django's template engine.
Access Django Data from Vue
The simplest way to do so is the built-in Django jscon_script filter.
This way you can immediately start using your Django models as data for your Vue instances.
In HTML:
{{ django_template_variable|json_script:"djangoData" }}
Then, in JavaScript, we load this data into a variable:
let jsVariable = JSON.parse(document.getElementById('djangoData').textContent);
And it is ready to use with Vue:
new Vue({
delimiters: ["[[", "]]"],
el: '#app',
data: jsVariable
})
Make async Backend Requests
One of the most frequent tasks of a Vue frontend is to make requests to a backend server application. With a full-stack Django application, we don't have to do this for every user interaction. In some cases, a full page reload might be perfectly fine, and Django's templating system provides all kinds of advantages. But to enhance user experience and to reap the full benefits of using Vue, we may still want to make backend requests in some places.
Vue itself cannot handle requests. In this post, I will use axios, because it is also recommended in the official Vue Docs. Other alternatives are perfectly fine too.
To pass Django's CSRF protection mechanism, axios needs to include the respective cookie in its requests. The easiest way to accomplish this is to set global axios defaults:
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
Alternatively, we could also create an axios instance with the required settings:
var instance = axios.create({
xsrfCookieName: 'csrftoken',
xsrfHeaderName: "X-CSRFTOKEN",
});
Your Django template needs to contain the tag {% csrf_token %}
or, alternatively, the respective view must use the decorator ensure_csrf_cookie()
.
The rest of Django's default session backend for authentication will work out of the box, meaning that you can annotate your backend services with things like loginRequired
and it will just work.
To make the request, we can use axios as usual:
axios.post('/django/backend/endpoint', {
data: jsVariable
})
.then(function (response) {
// handle response
})
.catch(function (error) {
// handle error
});
This call can be done within a Vue instance's mounted
hook or any other place where you can put JavaScript code.
If you activated CSRF_USE_SESSIONS
or CSRF_COOKIE_HTTPONLY
in your Django settings, you need to read the CSRF token from the DOM. For more details, see the official Django docs.
Conclusion
When you google for Django + Vue, most results will be focused on using Django for your backend and Vue for a separate frontend project. Having two independent projects increases complexity, and you lose access to Django's template system, which is a very powerful timesaver. On the other hand, access to a frontend framework such as Vue can do wonders for web applications that go beyond CRUD functionality.
Fortunately, we do not need to decide between the two. This guide shows that you can have the cake and eat it too!
This post was originally published on my personal blog site at https://tkainrad.dev/posts/use-vuejs-with-django/
Posted on September 2, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.