Plotly
Install Plotly:
You can install Plotly using pip:
pip install plotlyviews.py
from django.shortcuts import render
import plotly.graph_objs as go
def chart_view(request):
# Fetch data from the database or any other source
data = [1, 3, 2, 4, 3, 5]
# Create a Plotly trace
trace = go.Scatter(x=list(range(len(data))), y=data, mode='lines+markers')
# Create a Plotly layout
layout = go.Layout(title='Sample Chart', xaxis=dict(title='X-axis'), yaxis=dict(title='Y-axis'))
# Create a Plotly figure
figure = go.Figure(data=[trace], layout=layout)
# Convert the Plotly figure to JSON
chart_data = figure.to_json()
return render(request, 'chart_template.html', {'chart_data': chart_data})
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Plotly Chart Example</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="chart-container" style="width: 80%; margin: 0 auto;"></div>
<script>
// Load the Plotly chart data
var chartData = {{ chart_data|safe }};
// Create the Plotly chart
Plotly.newPlot('chart-container', chartData.data, chartData.layout);
</script>
</body>
</html>
Django + Chart.js
Django + Chart.js: A Step-by-Step Guide to Creating a Chart
Create a Model to Store Data
We will create a model named YourModel to hold the data we want to visualize.
Create the Model: In charts/models.py, define a simple model with fields label and value:
# product/models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
sales = models.IntegerField()
def __str__(self):
return self.name
Run Migrations
After creating the model, run the migrations to update the database schema.
python manage.py makemigrations
python manage.py migrate
Add Some Sample Data
You can add some sample data to the database using Django’s admin panel or through the Django shell.
Using the Django Shell
python manage.py shell
from product.models import Product
Product.objects.create(name='Product A', sales=120)
Product.objects.create(name='Product B', sales=90)
Product.objects.create(name='Product C', sales=150)
Product.objects.create(name='Product D', sales=60)
Product.objects.create(name='Product E', sales=200)
Create the View for Chart Data
Now, we will create a view to fetch the product data and pass it to the template. The data will be converted into JSON format for use in Chart.js.
# product/views.py
from django.shortcuts import render
from .models import Product
import json
def chart_data(request):
data = Product.objects.all()
chart_data = []
for item in data:
chart_data.append({
'label': item.name, # Product name as label
'value': item.sales, # Product sales as value
})
chart_data_json = json.dumps(chart_data)
return render(request, 'chart_template.html', {'chart_data_json': chart_data_json})
Create the Template
Next, we will create the template that will render the chart using Chart.js.
<!-- product/templates/chart_template.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product Sales Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<h2>Product Sales Data</h2>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var chartData = {{ chart_data_json|safe }};
var labels = chartData.map(function(item) {
return item.label;
});
var values = chartData.map(function(item) {
return item.value;
});
var myChart = new Chart(ctx, {
type: 'bar', // Chart type (you can change it to 'line', 'pie', etc.)
data: {
labels: labels,
datasets: [{
label: 'Sales',
data: values,
backgroundColor: 'rgba(54, 162, 235, 0.2)', // Chart bar color
borderColor: 'rgba(54, 162, 235, 1)', // Bar border color
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
</body>
</html>
``