10

Using VueJS Alongside Django

 4 years ago
source link: https://tkainrad.dev/posts/use-vuejs-with-django/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introduction

I am currently working on a very exciting project. 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({
  delimeters: ["[[", "]]"],
  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({
  delimeters: ["[[", "]]"],
  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. First, we need to setup a csrftoken :

axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";

var instance = axios.create({
    xsrfCookieName: 'csrftoken',
    xsrfHeaderName: "X-CSRFTOKEN",
});

Your Django view needs to contain the the template tag {% csrf_token %} or use the view 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.

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!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK