Developing a dynamic web application using the Django framework along with the Vue.js library and Highcharts for

I am currently working on a data visualization web app using Django, Highcharts, and JQuery. I have recently transitioned from JQuery to Vue JS and I am struggling with fetching JSON data from a specific URL. Below is the code snippet:

Template

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Django Highcharts Example</title>
</head>
<body>
  <div id="container" data-url="{% url 'async_chart_data' %}"></div>
  <script src="https://code.highcharts.com/highcharts.src.js"></script>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script>
    $.ajax({
      url: $("#container").attr("data-url"),
      dataType: 'json',
      success: function (data) {
        Highcharts.chart("container", data);
      }
    });
  </script>
</body>
</html>

Views.py

 def chart_view(request):
     return render(request,'chart.html')

 def chart_data(request):
     dataset = Passenger.objects.values('embarked')\
     .exclude(embarked='')\
     .annotate(total=Count('embarked'))\
     .order_by('embarked')

     port_name = dict()
     for choices_tuple in Passenger.PORT_CHOICES:
         port_name[choices_tuple[0]] = choices_tuple[1]

     #Highcharts visualization config
     pie_chart = {
        'chart' : {'type':'pie'},
        'title' : {'text' : 'PORTS'},
        'series': [{
           'name' : 'Departure Ports',
           'data' : list(map(lambda row: {'name' : port_name[row['embarked']],
            'y' : row['total']},dataset))
       }]
     }

     return JsonResponse(pie_chart)

Models.py

 from django.db import models

 class Passenger(models.Model):
       MALE = 'M'
       FEMALE = 'F'

      SEX_CHOICES = (
         (MALE, 'male'),
         (FEMALE, 'female')
       )

       CHERBOURG = 'C'
       QUEENSTOWN = 'Q'
       SOUTHAMPTON = 'S'

        PORT_CHOICES = (
           (CHERBOURG, 'Cherbourg'),
           (QUEENSTOWN, 'Queenstown'),
           (SOUTHAMPTON, 'Southampton'),
       )

      name = models.CharField(max_length=100, blank=True)
      sex = models.CharField(max_length=1, choices=SEX_CHOICES)
      survived = models.BooleanField()
      age = models.FloatField(null=True)
      ticket_class = models.PositiveSmallIntegerField()
      embarked = models.CharField(max_length=1, choices=PORT_CHOICES)

      def __str__(self):
         return self.name

I want to switch from using JQuery to fetch JSON data to using Vue JS. Can someone guide me on how to do that?

EDIT: I have resolved this issue and encountered another problem mentioned Here

Answer №1

Finally solved the case by utilizing vue js life cycle hooks. Despite the page loading slowly (approximately 4 to 7 seconds), it is functional. Below is the code snippet of my template:

<!DOCTYPE html>
<html>
<head>
<title>Using Vue Axios</title>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4d2d1c1e4968a918a9592">[email protected]</a>/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
</head>
<body>
<div id="app">[[dataTitanic]]</div>
<h1>The Chart Is Shown Below : </h1>
<div id="container"></div>
<script type="text/javascript">
var url = "{% url 'async_chart_data' %}";
var app = new Vue({
delimiters : ['[[',']]'],
el : '#app',
data(){
return {
dataTitanic : null,
}
},
mounted(){
axios
  .get(url)
  .then(response => (this.dataTitanic = response['data']))
},
beforeUpdate(){
Highcharts.chart('container',this.dataTitanic)
}
})
</script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to use the jsonify method on a variable within an html file, the output is not displayed

Is it possible to store "jsonify" in a variable? I find the pure json format of "return jsonify(data)" unappealing, so I am looking for a way to enhance it using an HTML template with proper indentation. Here's the python code I have: from flask impo ...

Pressing the shortcut key will activate the function specified in ng-click,

I have been searching for a solution to my problem, but I haven't found anything that really helps. What I am looking for is a shortcut within an ng-click directive where there is only an if condition without an else expression. Essentially, I just wa ...

Creating Lists Using Instances

Currently experimenting with list comprehension and facing a challenge. class Coder(): def __init__(self, name, years_at_college=1, scripts_written=0): self.name = name self.experience = years_at_college self.bonus_points = ra ...

How can you efficiently manage Access & Refresh tokens from various Providers?

Imagine I am allowing my users to connect to various social media platforms like Facebook, Instagram, Pinterest, and Twitter in order to use their APIs. As a result, I obtain access tokens for each of these providers. Based on my research, it seems advisa ...

I encountered an error when trying to locate an element using its class name and xpath in Selenium with Python. The error message displayed was `ERR_SSL_VERSION_OR_CIPHER_MISMATCH`

I am in need of gathering information from a specific webpage that cannot be referenced openly due to its adult content. In order to proceed further, I must first click the age confirmation button on the page. My sole interest is to retrieve the page' ...

How can we programmatically add click handlers in Vue.js?

Currently attempting to add some computed methods to an element based on mobile viewports exclusively. Here is a simplified version of my current project: <a class="nav-link float-left p-x-y-16" v-bind:class={active:isCurrentTopicId(t.id)} @click="onTo ...

ReactJS: Understanding the Interconnectedness of Components

In my application, I have two main components: Table (which is a child of Tables) and Connection (which is a child of Connections). Both Tables and Connections are children of the App component. The issue I am facing is that the Table component needs to be ...

Switch between the table data elements in an .hta document

The response provided by Dr.Molle in a previous post here was accurate, but it only functioned with <div>. I am required to utilize <table>. Though I found a script that works flawlessly outside of my VBScript, it does not work when embedded in ...

Issue encountered during CNN construction in PyTorch: "Spatial targets must be in batches (3D tensors), but received targets with size: [1, 2, 64, 64]"

I'm in the process of constructing a Convolutional Neural Network (CNN) inspired by the research paper located at: (). For my project, I am utilizing images obtained from the LAB-color space. I have developed a data loader to handle the "l and a, b" ...

Module Augmentation for extending Material UI theme is not functioning as expected

I'm having trouble expanding upon the Theme with Material UI because an error keeps popping up, indicating that I am not extending it correctly. The error message states: Property 'layout' is missing in type 'Palette' but required ...

Using Python to create a customizable progress bar and writing it to a file

I am facing an issue with executing a Python script that runs a Perl script as part of its functionality. I am capturing the stdout and stderr using the subprocess module, following this pseudo code: import subprocess as sp import sys perl_script='/u ...

What could be causing JavaScript fetch to only send OPTIONS requests instead of the expected calls?

I'm having an issue with my AJAX request using javascript fetch. It's only sending an OPTIONS call and not proceeding to make further calls. What's strange is that the response header seems fine, and $.ajax is working as expected. Check out ...

Experiencing the 'Rich Embed fields cannot be empty' error even though my code is functioning properly

My code is set up to log when someone edits a message on Discord. It captures the original message, the edited message, the channel, and more details. Everything seems to be working fine, but I keep encountering an error indicating that my RichEmbed fields ...

Delete the tag that comes before

Is there a specific tag like: <p id="name" onclick="javascript:var ele=context(this);">sumtext here</p><br> <p id="name" onclick="javascript:var ele=context(this);">newtext here</p><br> <script ...

How can I remove a row from an MVC webgrid using an ajax call?

Within my MVC Razor view, I have a partial view containing webgrid data. My goal is to include an action link to delete a specific row of data. To accomplish this, I crafted the following JavaScript function: function delMeal(pid) { if (confirm("Do yo ...

Is there a way to prevent the imported JQuery from causing issues with current code implementations?

Being a novice developer in Html/Javascript/CSS/Jquery coding, I recently encountered an issue while integrating Jquery into my project. When I imported Jquery, the styling of simple buttons went haywire. Jquery worked perfectly fine when using its classes ...

What are some ways to keep the text within the boundaries of the input box?

How can I prevent the letters from extending beyond the bar when typing a lot of characters? Your assistance in resolving this issue is greatly appreciated. <div id="tasks-container"> <div id="tasks-header"> ...

Having trouble loading CSS and JavaScript files after building with vue-cli and webpack?

I'm working with koa2 as the backend and using koa-swig to handle page rendering. The project structure looks like this: https://i.stack.imgur.com/zYGNS.png Within the dist folder, you'll find index.html and a static directory containing all CSS ...

Node Js issue stemming from unaddressed promises leading to rejection

Hi, everyone! I'm currently facing some challenges while trying to deploy this API. The error message I keep getting is: "UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error may have occurred due to either throwing inside an asyn ...

When trying to insert JavaScript into the console, a section of the code fails to execute

In this code snippet, I am fetching the most common English words from Wikipedia, extracting all the words from the page, and then filtering out the commonly used words: // get table data from most common words var arr = []; $.ajax({ url: 'https:/ ...