What steps should I follow to make the example in django-graphos work correctly?

Attempting to troubleshoot a basic example of django-graphos using the provided code. However, I'm encountering an error message in Chrome Inspector saying 'Uncaught ReferenceError $ is not defined', with a red dot indicating the issue right after $(function () { - and no graph is displayed. Despite this, it appears that the template is being generated correctly, as indicated in the inspector output below.

Chrome Inspector Output:

<html>
<h1>- Django-graphos Chart 1 - </h1>
<head>
        <script type = "text/javascript" src = "js/jquery-1.11.2.js"></script>
        <script src = "js/flot/jquery.flot.js"></script>
     <div id="xlZGoSiTTr" style="width:800px;height:400px;"></div>
<script type="text/javascript">
$(function () {
    $.plot(
        $("#xlZGoSiTTr"), 
        [{"data": [["2004", 1000], ["2005", 1170], ["2006", 660], ["2007", 1030]], "label": "Sales"}, {"data": [["2004", 400], ["2005", 460], ["2006", 1120], ["2007", 540]], "label": "Expenses"}], 
        {"series": {"lines": {"show": "true"}}, "legend": {"position": "ne"}, "title": "Chart"}
    );
});
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>

views.py:

from django.shortcuts import render

from django.http import HttpResponse
from django.template import RequestContext, loader
from graphos.sources.simple import SimpleDataSource
from graphos.renderers import flot
from django.shortcuts import render_to_response


def do_graph(request):
    # get data
    data = [
    ['Year', 'Sales', 'Expenses'],
    ['2004', 1000, 400],
    ['2005', 1170, 460],
    ['2006', 660, 1120],
    ['2007', 1030, 540]
    ]
    chart = flot.LineChart(SimpleDataSource(data=data))
    #context = RequestContext( request, `enter code here`{'chart':chart.as_html(),'data':data})
    #template = loader.get_template('chart.html')
    #return HttpResponse(template.render(context))
    #return render(request, 'chart.html')
    return render_to_response('chart.html', {'chart': chart})

chart.html:

<html>
<h1>- Django-graphos Chart 1 - </h1>
<head>
        <script type = "text/javascript" src = "{{ STATIC_URL }}js/jquery-1.11.2.js"></script>
        <script type = "text/javascript" src = "{{ STATIC_URL }}js/flot/jquery.flot.js"></script>
     {{chart.as_html}}
</head>
<body>
<div id="container"></div>
</body>
</html>

The two JS files appear to be loading successfully with a status 200 response from the Django server. Any suggestions for resolving this issue with django-graphos would be highly appreciated. Thank you, Ron.

Answer №1

Discovering the solution to my own query! The issue stemmed from a faulty expression when accessing the jquery javascript files, despite the nginx log indicating successful retrieval with a 200 status code.

Below is the corrected syntax (with additional code for enhanced Flot features since the original inquiry)

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.tab { margin-left: 220px; }
</style>
        <script type = "text/javascript" src = "/static/js/jquery-1.11.2.js"></script>
        <script type = "text/javascript" src = "/static/js/flot/jquery.flot.js"></script>
        <script type = "text/javascript" src = "/static/js/flot/jquery.flot.time.js"></script>
        <script type = "text/javascript" src="/static/js/flot/date.js"></script>
        <script type = "text/javascript" src="/static/js/flot/jquery.flot.axislabels.js"></script>
<p class="tab"><font size=28 color="red">- Tank Water Level - </font></p>
        {{chart.as_html}}
</head>
<body>

</body>
</html> 

The views.py configuration was accurate. Now operational with Flot chart options demonstrated below. The get_table() function returns an n x 2 data matrix, with field names in the first row.

def do_graph(request):
    # obtain data
    data = get_table()
    chart = flot.LineChart(SimpleDataSource(data=data),options={'series':{'color':'orange'}, 'lines': {'lineWidth': 2, 'fill':1, 'fillColor': {'colors':["rgba(0, 0, 153, 0.4)","rgba(255, 255, 255,0.4)"]} }, 'points':{'symbol':'circle'},'xaxis':{'mode':'time', 'timezone':'browser', 'axisLabel':'Date Time', 'axisLabelUseCanvas':'true', 'axisLabelFontSizePixels': 20,'axisLabelFontFamily':'Arial','color':'red'},'yaxis':{'min':50, 'max':400, 'tickSize': 50, 'axisLabel':'Centimeters', 'axisLabelUseCanvas':'true', 'axisLabelFontSizePixels': 20,'axisLabelFontFamily':'Arial'},'grid':{'color':800}})
    return render_to_response('chart.html', {'chart': chart})

The added Flot options and jquery plugins result in a graph displaying date time correctly on the x-axis, utilizing javascript timestamps in the data's initial column. Axis labels are incorporated using the supplementary 'axislabels' jquery flot plugin.

Warm regards, Ron

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

Tips on accessing a file in v-file-input

<v-file-input accept="image/*" label="File input" v-model="chosenFile" ></v-file-input> I'm working with Vue.js. How can I access the content of the files? var reader = new FileReader(); var img = ...

The reload button fails to refresh the page

When I try to reload the page by pressing a button, it doesn't work and I'm unsure of the issue. I am utilizing handlebars, so technically all the provided code is within a <body> tag. The POST request is sent successfully, but the script ...

What could be causing the repetition of log information in Django?

While attempting to retrieve logs from my Django project, I have noticed that the log messages are being duplicated in different formats. Where should I start to fix this issue of duplicate logs? LOGGING = { 'version': 1, 'disable_e ...

Develop a jQuery dialog box without assigning an ID

I need help with jQuery to create a dialog that opens and then populates with values. When I tried to create the dialog using jQuery, it kept using old values because the div already existed on the page. I want to create a new instance of the dialog usin ...

Activating the spinning wheel page-loading indicator in the browser through Socket.IO

Currently, I am constructing a web application using Node.js along with Socket.IO for managing data transfer between the client and server components. The central component of my web app is a content feed. To fetch the contents of the newsfeed, my client- ...

Using jQuery to transform a JSON array within a JSON object into an array

I am attempting to convert the JSON data below: { "questions": [ { "question#1": "How much is 3+1", "correct answer": 1, "answers": { "ans#1": "5", "ans#2": "4", ...

HTML form submission with a grid of multiple choice options

I have created my own multiple choice grid: <div style="overflow-x:auto;"> <table class="w-100"> <tr> <td class="border"></td> <td class="border">Yes</td> <td class="border">No</ ...

I am encountering issues with my THREE.js RawShaderMaterial

I haven't encountered any issues when loading shaders created by others into THREE.js, but I've hit a roadblock when trying to create and run my own shader. The shader works perfectly on the platform where I designed it (), but it doesn't fu ...

The charAt function in a basic JavaScript if statement is failing to execute

When a user inputs a number that does not start with 6 or 9, an error occurs: console.log($(this).val().charAt(0)); if($(this).val().charAt(0) != 6 || $(this).val().charAt(0) != 9){ x=false; }else { x=true; } The console.log function corre ...

Can one extract a property from an object and assign it to a property on the constructor?

Currently working with TypeScript, I am looking to destructure properties from an object. The challenge lies in the fact that I need to assign it to a property on the constructor of the class: var someData = [{title: 'some title', desc: 'so ...

Prevent automatic scrolling of a div in jQuery while it is being hovered over

After addressing a previous question, I have further refined the script but encountered an issue at the final step. The current functionality involves a div automatically scrolling 50px at a time until it reaches the bottom, then it scrolls back to the to ...

Submitting a nested JSON body in ASP MVC

I'm currently struggling to send a nested JSON body to an API, and I've tried a few different approaches without success. The JSON values are sourced from multiple models, making it quite complex for me to handle. Any assistance or guidance on th ...

Searching for documents in MongoDB using a reference field

I'm working with two Mongo schemas: User: { _id: ObjectId, name: String, country: ObjectId // Reference to schema Country } Country: { _id: ObjectId, name: String } My goal is to retrieve all users who are from "VietNam". Could you provi ...

Trigger the execution of the second function upon the successful completion of the first

In the following code, my concept is to display: The clicked kingdom (clicked_id) initiates an attack on (clicked_id). https://i.stack.imgur.com/Bx8QW.png https://i.stack.imgur.com/Cg2GL.png https://i.stack.imgur.com/gUNxM.png How can I trigger the sec ...

Tips for adding animation to a React state value change triggered by an input

In my React application, I have a form with multiple fields that each contain a text input and a range input. Currently, both inputs share the same state value and onChange function to keep them synchronized. However, I would like to add an animation effe ...

Is there a way to still access the data from a radio button even if it hasn't been selected?

I'm currently working on a questionnaire feature and facing an issue where I need to capture all answers, even if the radio button is not checked. Here's a snippet of the HTML code: $('input:radio').each(function () { if ($(this). ...

What is the best way to display a loader when utilizing AJAX with jQuery?

I am having trouble implementing a loader in my ajax jQuery call. My goal is to display a loader while the ajax request is fetching data from an API and hide it once the request is completed. I have split this functionality into 2 separate JavaScript fil ...

The rotation function of a THREE.js object seems to be malfunctioning

Currently, I am facing an issue with a Blender object that I have successfully displayed on my web page using THREE.js. However, for some reason the object is not rotating when my loop function is called. In my approach to working with JavaScript, I am tr ...

Ways to direct to dashboard if a user is logged in using AngularJS

As a newcomer to AngularJS, I am facing an issue with redirecting my page to the dashboard once the user has logged in. I receive an access token after login, which I save in cookies. Despite trying solutions from Stack Overflow, I have not been able to re ...

Dynamically remove a MongoDB entry with precision

I'm having trouble deleting an entry in MongoDB based on the id variable. Even when I pass the id as a parameter to the method, it doesn't seem to work. I've double-checked the variable inside the method and I'm confident that it has th ...