在Django项目中配置django-chartjs示例失败,寻求解决方案
Hey there, let's troubleshoot your django-chartjs setup step by step. You've already done the basics—installing dependencies, adding the app to INSTALLED_APPS—so let's dig into the common pitfalls that might be causing your issue.
First, Let's Cover the Most Likely Fixes
1. Double-Check Your URL Configurations
This is the #1 overlooked step for this setup. You have the views defined, but you need to map them to URLs in your app's urls.py file. Without this, the Ajax call to fetch chart data will fail with a 404 error.
Add these lines to your urls.py:
from django.urls import path from .views import line_chart, line_chart_json urlpatterns = [ path('line-chart/', line_chart, name='line_chart'), path('line-chart/json/', line_chart_json, name='line_chart_json'), ]
2. Verify Static Files Are Loading Correctly
- Make sure
Chart.min.jsexists in your project'sstatic/js/directory. - Open your browser's developer tools (F12), go to the Network tab, and check that
Chart.min.jsloads with a 200 status code (no 404 errors). - For Django 3.0+, replace
{% load staticfiles %}in your template with{% load static %}—it's the updated, recommended way to load static resources.
3. Confirm View Inheritance & Data Format
Ensure you're importing the correct base view from django-chartjs. Your view should start with:
from chartjs.views.lines import BaseLineChartView
To test if your data endpoint works, manually visit the line_chart_json URL (e.g., http://localhost:8000/line-chart/json/) in your browser. You should see a valid JSON structure like this:
{ "labels": ["January", "February", "March", "April", "May", "June", "July"], "datasets": [ {"label": "Central", "data": [75,44,92,11,44,95,35]}, {"label": "Eastside", "data": [41,92,18,3,73,87,92]}, {"label": "Westside", "data": [87,21,94,3,90,13,65]} ] }
4. Update jQuery for Compatibility
You're using jQuery 1.10.0, which is quite outdated and might clash with newer versions of Chart.js. Swap it for a modern stable version in your template:
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
5. Add Error Handling to Debug the Ajax Call
Modify your template's JavaScript to log errors, which will help you pinpoint issues faster:
<script type="text/javascript"> $.get('{% url "line_chart_json" %}', function(data) { var ctx = $("#myChart")[0].getContext("2d"); new Chart(ctx, { type: 'line', data: data }); }).fail(function(jqXHR, textStatus, errorThrown) { console.log("Failed to load chart data:", textStatus, errorThrown); console.log("Request URL:", '{% url "line_chart_json" %}'); }); </script>
Modified Working Code Snippets
Updated Template (test.html)
{% load static %} <html> <head> <title>django-chartjs line chart demo</title> <!--[if lte IE 8]> <script src="{% static 'js/excanvas.js' %}"></script> <![endif]--> </head> <body> <h1>Some Line Charts loaded in Ajax!</h1> <canvas id="myChart" width="500" height="400"></canvas> <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script type="text/javascript" src="{% static 'js/Chart.min.js' %}"></script> <script type="text/javascript"> $.get('{% url "line_chart_json" %}', function(data) { var ctx = $("#myChart")[0].getContext("2d"); new Chart(ctx, { type: 'line', data: data }); }).fail(function(jqXHR, textStatus, errorThrown) { console.log("Failed to load chart data:", textStatus, errorThrown); console.log("Request URL:", '{% url "line_chart_json" %}'); }); </script> </body> </html>
Updated View Code
from django.views.generic import TemplateView from chartjs.views.lines import BaseLineChartView class LineChartJSONView(BaseLineChartView): def get_labels(self): return ["January", "February", "March", "April", "May", "June", "July"] def get_providers(self): return ["Central", "Eastside", "Westside"] def get_data(self): return [[75, 44, 92, 11, 44, 95, 35], [41, 92, 18, 3, 73, 87, 92], [87, 21, 94, 3, 90, 13, 65]] line_chart = TemplateView.as_view(template_name='main/mark/test.html') line_chart_json = LineChartJSONView.as_view()
After making these changes, restart your Django server and test the page again. If you still see issues, check the browser's console for specific error messages—they'll tell you exactly what's going wrong.
内容的提问来源于stack exchange,提问作者NiPa

