0% found this document useful (0 votes)
10 views7 pages

Admin Chart

This document contains code for rendering interactive charts on a dashboard. It includes code to generate monthly and yearly collection charts from donation data, handle date filtering, and display the charts. JavaScript code updates chart titles and applies filters when dropdowns are changed.

Uploaded by

bithorthaagam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views7 pages

Admin Chart

This document contains code for rendering interactive charts on a dashboard. It includes code to generate monthly and yearly collection charts from donation data, handle date filtering, and display the charts. JavaScript code updates chart titles and applies filters when dropdowns are changed.

Uploaded by

bithorthaagam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 7

{% extends 'dashboard/base.

html' %}
{% load static %}

{% block content %}
<style>
/* Custom CSS */
.chart-container {
border: 1px solid #dee2e6; /* Gray border */
border-radius: 5px; /* Rounded corners */
padding: 20px; /* Padding around the chart */
background-color: #fff; /* White background color */
margin-top: 20px; /* Add margin to separate from title */
}

.chart-container h2 {
color: #343a40; /* Dark text color */
margin-bottom: 20px; /* Bottom margin for heading */
}

/* Optional: Add more styling as needed */


</style>

<!-- Dropdown for selecting month and year -->


<div class="container mt-4">
<div class="row justify-content-center">
<div class="col-md-4 mb-3">
<select id="month-dropdown" class="form-select">
{% for month in months %}
<option value="{{ month.0 }}" {% if month.0 == selected_month
%}selected{% endif %}>{{ month.1 }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-4 mb-3">
<select id="year-dropdown" class="form-select">
{% for year in years %}
<option value="{{ year }}" {% if year == selected_year %}selected{% endif
%}>{{ year }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-4 mb-3">
<button id="apply-filter-btn" class="btn btn-primary">Apply Filter</button>
</div>
</div>
</div>

<!-- Display month-wise chart -->


<hr>
<div class="container my-4">
<h2 id="monthly-collection-title" class="text-center">{{ month_title }}</h2>
<!-- Display month-wise chart title -->
<div id="month_chart_div" class="chart-container">
{{ month_chart_div|safe }}
</div>
</div>

<!-- Display year-wise chart -->


<hr>
<!-- Dropdown for selecting year for year-wise chart -->
<div class="container mt-4">
<div class="row justify-content-center">
<div class="col-md-4 mb-3">
<select id="year-dropdown-year-chart" class="form-select">
{% for year in years %}
<option value="{{ year }}" {% if year == selected_year_for_year_chart
%}selected{% endif %}>{{ year }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-2 mb-3">
<button id="apply-year-filter-btn" class="btn btn-primary">Apply
Filter</button>
</div>
</div>
</div>

<!-- Display year-wise chart -->


<hr>
<div class="container my-4">
<h2 id="yearly-collection-title" class="text-center">{{ year_title }}</h2> <!--
Display year-wise chart title -->
<div id="year_chart_div" class="chart-container">
{{ year_chart_div|safe }}
</div>
</div>

<script src="{% static 'js/jquery.min.js' %}"></script>


<script>
// JavaScript code for handling dropdown selection and applying filters for
month-wise chart
document.getElementById('apply-filter-btn').addEventListener('click', function()
{
var selectedMonth = document.getElementById('month-dropdown').value;
var selectedYear = document.getElementById('year-dropdown').value;
updateMonthlyCollectionTitle(selectedMonth, selectedYear); // Update monthly
collection title
window.location.href = '/dashboard/admin_chart/?month=' + selectedMonth +
'&year=' + selectedYear;
});

// JavaScript code for handling dropdown selection and applying filters for year-
wise chart
document.getElementById('apply-year-filter-btn').addEventListener('click',
function() {
var selectedYear = document.getElementById('year-dropdown-year-chart').value;
updateYearlyCollectionTitle(selectedYear); // Update yearly collection title
window.location.href = '/dashboard/admin_chart/?year_for_year_chart=' +
selectedYear;
});

// Update monthly collection title


function updateMonthlyCollectionTitle(selectedMonth, selectedYear) {
var monthName = getMonthName(selectedMonth);
document.getElementById('monthly-collection-title').innerText = 'Collection
Amount for ' + monthName + ' ' + selectedYear;
}
// Update yearly collection title
function updateYearlyCollectionTitle(selectedYear) {
document.getElementById('yearly-collection-title').innerText = 'Yearly
Collection for ' + selectedYear;
}

// Function to get month name from month number


function getMonthName(monthNumber) {
var d = new Date();
d.setMonth(monthNumber - 1); // Months are 0-indexed
return d.toLocaleString('en-US', { month: 'long' });
}
</script>
{% endblock %}

from django.contrib.auth.decorators import login_required, user_passes_test


from django.http import JsonResponse
from django.shortcuts import render
from main.models import Donation
import plotly.offline as opy
import plotly.graph_objs as go
import pandas as pd
from datetime import datetime
import calendar
from django.utils import timezone

def render_chart(data, title):


df = pd.DataFrame(data)
df['dates'] = pd.to_datetime(df['dates'])

# Sort the DataFrame by dates to ensure consistent ordering


df = df.sort_values(by='dates')

fig = go.Figure()

# Add trace for the line chart


fig.add_trace(go.Scatter(
x=df['dates'],
y=df['amounts'],
mode='lines+markers',
name='Collection Amount',
line=dict(color='#1f77b4', width=2), # Blue line
marker=dict(color='#1f77b4', size=8, line=dict(color='#ffffff', width=1)),
# Blue markers
))

# Update layout with the dynamically generated title


fig.update_layout(
title=title,
xaxis_title='Date',
yaxis_title='Amount',
template='plotly_white',
font=dict(family='Arial, sans-serif', size=12, color='#333'), # Darker
font color
margin=dict(l=60, r=60, t=80, b=60), # Increased margins
plot_bgcolor='#f5f5f5', # Light gray background color
paper_bgcolor='#f5f5f5', # Light gray paper background color
xaxis=dict(
showline=True,
showgrid=False,
showticklabels=True,
linecolor='#333',
linewidth=1,
ticks='outside',
tickfont=dict(family='Arial, sans-serif', size=10, color='#333'), #
Darker axis line and ticks
),
yaxis=dict(
showline=True,
showgrid=True,
showticklabels=True,
linecolor='#333',
linewidth=1,
ticks='outside',
tickfont=dict(family='Arial, sans-serif', size=10, color='#333') #
Darker axis line and ticks
),
)

plot_div = opy.plot(fig, auto_open=False, output_type='div')

return plot_div

def render_year_chart(data, selected_year=None):


# Prepare data for year-wise chart
year_data = {
'dates': [],
'amounts': []
}

# Group data by month and sum the amounts for each month
monthly_collection = {}
for donation in data:
month_year_key = donation.service_date.strftime('%B-%Y')
if month_year_key not in monthly_collection:
monthly_collection[month_year_key] = 0
monthly_collection[month_year_key] += donation.amount

# Convert the grouped data into lists for Plotly


for month_year, amount in monthly_collection.items():
year_data['dates'].append(month_year)
year_data['amounts'].append(amount)

# Define the order of months for correct ordering on the X-axis


ordered_months = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
# Sort the data based on the order of months
sorted_data = sorted(zip(year_data['dates'], year_data['amounts']), key=lambda
x: ordered_months.index(x[0].split('-')[0]))

# Unpack the sorted data only if it exists


if sorted_data:
sorted_dates, sorted_amounts = zip(*sorted_data)
else:
sorted_dates, sorted_amounts = [], []

fig = go.Figure()

# Add trace for the line chart only if there is data


if sorted_dates and sorted_amounts:
fig.add_trace(go.Scatter(
x=sorted_dates,
y=sorted_amounts,
mode='lines+markers',
name='Monthly Collection',
line=dict(color='#1f77b4', width=2), # Blue line
marker=dict(color='#1f77b4', size=8, line=dict(color='#ffffff',
width=1)), # Blue markers
))

# Update layout
if selected_year is not None:
title = f'Monthly Collection for {selected_year}'
else:
current_year = datetime.now().year
title = f'Monthly Collection for {current_year}'

fig.update_layout(
title=title,
xaxis_title='Month',
yaxis_title='Amount',
template='plotly_white',
font=dict(family='Arial, sans-serif', size=12, color='#333'), # Darker
font color
margin=dict(l=60, r=60, t=80, b=60), # Increased margins
plot_bgcolor='#f5f5f5', # Light gray background color
paper_bgcolor='#f5f5f5', # Light gray paper background color
xaxis=dict(
showline=True,
showgrid=False,
showticklabels=True,
linecolor='#333',
linewidth=1,
ticks='outside',
tickfont=dict(family='Arial, sans-serif', size=10, color='#333'), #
Darker axis line and ticks
categoryorder='array', # Specify ordering for categorical axis
categoryarray=ordered_months # Order the months according to the
predefined list
),
yaxis=dict(
showline=True,
showgrid=True,
showticklabels=True,
linecolor='#333',
linewidth=1,
ticks='outside',
tickfont=dict(family='Arial, sans-serif', size=10, color='#333') #
Darker axis line and ticks
),
)

plot_div = opy.plot(fig, auto_open=False, output_type='div')

return plot_div, sorted(year_data['dates'])


# Return the chart div and sorted year options

@user_passes_test(lambda u: is_administrator(u))
@csrf_exempt
@login_required
def admin_chart(request):
current_month = datetime.now().month
current_year = datetime.now().year

# Fetch all donations


donations = Donation.objects.exclude(service_date=None)

# Get unique years from donations


years = set(donation.service_date.year for donation in donations if
donation.service_date)

# Get selected month and year from the request


selected_month = int(request.GET.get('month', current_month))
selected_year = int(request.GET.get('year', current_year))

# Filter donations based on selected month and year


filtered_donations = donations.filter(service_date__month=selected_month,
service_date__year=selected_year)

# Prepare data for month-wise chart


month_data = {
'dates': [donation.service_date for donation in filtered_donations],
'amounts': [donation.amount for donation in filtered_donations],
}

# Generate month-wise chart div


month_title = f'Collection Amount for {calendar.month_name[selected_month]}
{selected_year}'
month_chart_div = render_chart(month_data, month_title)

# Filter donations based on selected year for yearly collection


selected_year_for_year_chart = int(request.GET.get('year_for_year_chart',
current_year))
filtered_donations_yearly =
donations.filter(service_date__year=selected_year_for_year_chart)

# Generate year-wise chart div


year_chart_div, years_for_year_chart =
render_year_chart(filtered_donations_yearly, selected_year_for_year_chart)
# Prepare data for year-wise chart
year_title = f'Yearly Collection for {selected_year_for_year_chart}'

context = {
'month_chart_div': month_chart_div,
'year_chart_div': year_chart_div,
'months': [(i, calendar.month_name[i]) for i in range(1, 13)],
'years': sorted(years),
'years_for_year_chart': years_for_year_chart,
'selected_month': selected_month,
'selected_year': selected_year,
'selected_year_for_year_chart': selected_year_for_year_chart,# Provide
default value
'month_title': month_title, # Add the month title to the context
'year_title': year_title, # Add the year title to the context

return render(request, 'dashboard/admin_chart.html', context)

You might also like