Using VueJS Alongside Django

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

内容简介: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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

CLR via C#

CLR via C#

(美)Jeffrey Richter / 周靖 / 清华大学出版社 / 2010-9 / 99.00元

本书针对CLR和.NET Framework 4.0进行深入、全面的探讨,并结合实例介绍了如何利用它们进行设计、开发和调试。全书5部分29章。第Ⅰ部分介绍CLR基础,第Ⅱ部分解释如何设计类型,第Ⅲ部分介绍基本类型,第Ⅳ部分以实用特性为主题,第Ⅴ部分花大量篇幅重点介绍线程处理。 通过本书的阅读,读者可以掌握CLR和.NET Framework的精髓,轻松、高效地创建高性能应用程序。一起来看看 《CLR via C#》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具