Using VueJS Alongside Django

栏目: IT技术 · 发布时间: 6年前

内容简介: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 Dj

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!


以上所述就是小编给大家介绍的《Using VueJS Alongside Django》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Java语言程序设计

Java语言程序设计

(美) Y. Daniel Liang / 李娜 / 机械工业出版社 / 2011-6 / 79.00元

本书是Java语言的经典教材,畅销多年不衰。本书全面整合了Java的特性,采用“先讲基础”的教学方式,循序渐进地介绍了程序设计基础、面向对象程序设计、GUI程序设计等。另外,本书还全面且深入地覆盖了一些高级主题,包括算法和数据结构、并发、网络、国际化、高级GUI、数据库和Web程序设计等。 本书中文版由《Java语言程序设计 基础篇》和《Java语言程序设计 进阶篇》组成。基础篇对应原书的第......一起来看看 《Java语言程序设计》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具