Django - chart won't display values correctly - python

The goal here is to show each bar corresponding to association and total members as displayed below:
What I get is this one big block with no value.
Seems that no one has the same issue here that I have been looking for.
Still a newbie so appreciate all your help & guidance, folks!
models.py
class Member(models.Model):
member_no = models.AutoField(primary_key=True)
association = models.ForeignKey('Association')
...
class Association(models.Model):
asoc_name = models.CharField(max_length=50, null=True, blank=True)
class Meta:
db_table = 'Association'
def __str__(self):
return self.asoc_name
def __unicode__(self):
return self.asoc_name
class AssociationSummary(Association):
class Meta:
proxy = True
verbose_name = 'Association Summary'
verbose_name_plural = 'Association Summary'
admin.py
#admin.register(AssociationSummary)
class ChartAssociationAdmin(admin.ModelAdmin):
change_list_template = 'admin/chart_association.html'
def changelist_view(self, request, extra_context=None):
response = super(ChartAssociationAdmin, self).changelist_view(
request,
extra_context=extra_context,
)
try:
qs = response.context_data['cl'].queryset
except (AttributeError, KeyError):
return response
metrics = {
'association': Count('asoc_name'),
'total': Sum('member'),
}
response.context_data['summary'] = list(
qs.values('asoc_name', 'member').annotate(**metrics)
)
response.context_data['summary_total'] = dict(
qs.aggregate(**metrics)
)
summary_over_time = qs.values('asoc_name', 'member').annotate(total=Sum('member'))
summary_range = summary_over_time.aggregate(
low=Min('total'),
high=Max('total'),
)
high = summary_range.get('high', 0)
low = summary_range.get('low', 0)
response.context_data['summary_over_time'] = [{
'asoc_name': x['asoc_name'],
'total': x['total'] or 0,
'pct':\
((x['total'] or 0) - low) / (high - low) * 100
if high > low else 0,
} for x in summary_over_time]
return response
chart_association.html
{% extends 'admin/change_list.html' %}
{% block content_title %}
<h1> Association Summary </h1>
{% endblock %}
{% block result_list %}
<div class=”results”>
<table>
<thead>
<tr>
<th>
<div class=”text”>
<span>Association</span>
</div>
</th>
<th>
<div class=”text”>
<span>Total Members</span>
</div>
</th>
</tr>
</thead>
<tbody>
{% for row in summary %}
<tr class="{% cycle 'row1' 'row2' %}">
<td> {{ row.asoc_name }} </td>
<td> {{ row.total }} </td>
</tr>
{% endfor %}
</tr>
<tr style="font-weight:bold; border-top:2px solid #DDDDDD;">
<td> Total </td>
<td> {{ summary_total.total }} </td>
</tr>
</tbody>
</table>
</div>
<br>
<h2> Association Chart </h2>
<style>
.bar-chart {
display: flex;
justify-content: space-around;
height: 160px;
padding-top: 60px;
overflow: hidden;
}
.bar-chart .bar {
flex: 100%;
align-self: flex-end;
margin-right: 2px;
position: relative;
background-color: #79aec8;
}
.bar-chart .bar:last-child {
margin: 0;
}
.bar-chart .bar:hover {
background-color: #417690;
}
.bar-chart .bar .bar-tooltip {
position: relative;
z-index: 999;
}
.bar-chart .bar .bar-tooltip {
position: absolute;
top: -60px;
left: 50%;
transform: translateX(-50%);
text-align: center;
font-weight: bold;
opacity: 0;
}
</style>
<div class="results">
<div class="bar-chart">
{% for x in summary_over_time %}
<div class="bar" style="height:{{x.pct}}%">
<div class="bar-tooltip">
{{ x.total | default:0 }}<br>
{{ x.asoc_name }}
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
{% block pagination %}{% endblock %}

Related

how do I make a query for this issue ? in django

I'm having a 2 models Zone and DailyTask So I want to make a table in the front end(HTML)
that like image is shown below. U is used_tasks UN is unused_tasks T total_tasks
I want list this data for each zones for the currusponding timeslots this is my current code
model one Zone
class DailyTask(models.Model):
date = models.DateField()
zone = models.ForeignKey(Zone, on_delete=models.SET_NULL, null=True)
slot = models.ForeignKey(GeneralTimeSlot,related_name='daily_task', on_delete=models.CASCADE)
total_tasks = models.IntegerField(default=0)
used_tasks = models.IntegerField(default=0)
unused_tasks = models.IntegerField(default=0)
available_driver_slots = models.ManyToManyField(DriverTimeSlot)
model two Zone
class Zone(models.Model):
name = models.CharField(max_length=200)
coordinates = models.TextField(null=True, blank=True)
time slot view.py
def get(self, request, *args, **kwargs):
zones = Zone.objects.all()
today = datetime.date.today()
daily_task = DailyTask.objects.filter(date="2022-06-04")
return render(request, self.template_name, {'zones': zones, 'daily_tasks': daily_task})
template timeslotreport.html
{% extends 'macro-admin/base.html' %}
{% load crispy_forms_tags %}
{% block title %}
<title>Time Slot Report</title>
{% endblock %}
{% block content %}
<style type="text/css">
table {
border-collapse: collapse;
width: 100%;
}
td, th {
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
.button1 button{
border: 2px solid #3783b5;
border-radius: 5px;
padding: 5px 15px;
margin: 2px 0;
background-color: white;
width: 80px;
}
.under{
text-decoration:underline;
}
.order2 .card-title{
font-size: 25px!important;
}
.order2 button{
float: right;
padding: 10px 80px!important;
}
.marg{
padding-top: 50px;
}
.marg .row{
padding: 10px;
border-bottom: 1px solid #ece4e4;
}
.settle h4{
float: right;
padding: 5px 20px;
border: 2px solid #3783b5;
border-radius: 10px;
font-size: 15px;
}
.settle2 h4{
float: left;
padding: 5px 20px;
border: 2px solid #3783b5;
border-radius: 10px;
font-size: 15px;
}
input#birthday {
padding: 8px 10px!important;
min-width: 144px!important;
margin: 0 10px!important;
border-radius: 5px!important;
border: 1px solid #3f57ff!important;
background: #3f57ff!important;
color-scheme: dark!important;
}
</style>
<div class="container-fluid">
<div class="card" >
<div class="card-header order2">
<a class="card-title">
Time Slot Report
</a>
</div>
</div>
<div class="col-lg-12 col-md-12">
<div class="row my-2">
<div class="col-12 d-flex justify-content-md-center sort-index">
<form class="form-inline" action="/action_page.php">
<input type="date" id="birthday" name="birthday">
</form>
</div>
</div>
</div>
<hr>
<div class="card">
<!--<div class="card-header">
<h4 class="card-title">
Default
</h4>
</div> -->
<div class="card-body">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Time Slots</th>
{% for z in zones %}
<th scope="col">{{ z.name }}</th>
{% endfor %}
<th scope="col">Total used</th>
<th scope="col">Total unused</th>
<th scope="col">Total</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="col"></th>
{% for z in zones %}
<th scope="col">U / Un / T</th>
{% endfor %}
<th scope="col"></th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
{% for zone in zones|slice:":1" %}
{% for task in daily_tasks %}
{% if task.zone.id == zone.id %}
<tr>
<th class="align-middle text-center" scope="row">{{ task.slot.start_time.time }} - {{ task.slot.end_time.time }}</th>
{% for zo in zones %}
{% if task.zone.id == zone.id %}
<td class="align-middle text-center">{{ task.used_tasks }} / {{ task.unused_tasks }} / {{ task.total_tasks }}</td>
{% endif %}
{% endfor %}
</tr>
{% endif %}
{% endfor %}
{% endfor %}
</tbody>
</table>
</div>
</div>
<th class="align-middle text-center" scope="row">08:00:00AM - 09:00:00AM</th>
</tr>
<tr>
<th class="align-middle text-center" scope="row">09:00:00AM - 10:00:00AM</th>
</tr>
<tr>
<th class="align-middle text-center" scope="row">10:00:00AM - 11:00:00AM</th>
<td class="align-middle text-center">
{% for zone in zones %}
{% if zone.name == "Zone A" %}
{{ zone }}
{% endif %}
{% endfor %}
</td>
</tr>
<tr>
<th class="align-middle text-center" scope="row">12:00:00PM - 01:00:00PM</th>
</tr>
<tr>
<th class="align-middle text-center" scope="row">04:00:00PM - 05:00:00PM</th>
</tr>
<tr>
<th class="align-middle text-center" scope="row">05:00:00PM - 06:00:00PM</th>
</tr>
<tr>
<th class="align-middle text-center" scope="row">06:00:00PM - 07:00:00PM</th>
</tr>
<tr>
<th class="align-middle text-center" scope="row">07:00:00PM - 08:00:00PM</th>
</tr>
<tr>
<th class="align-middle text-center" scope="row">08:00:00PM - 09:00:00PM</th>
</tr>
<tr>
<th class="align-middle text-center" scope="row">09:00:00PM - 10:00:00PM</th>
</div>
<div class="card-body bg-fade">
<div class="d-flex align-items-center justify-content-center">
<nav aria-label="Page navigation" class="mr-3">
<ul class="pagination m-0">
<li class="page-item">
<a class="page-link" href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
<span class="sr-only">Previous</span>
</a>
</li>
<li class="page-item active"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
<li class="page-item">
<a class="page-link" href="#" aria-label="Next">
<span aria-hidden="true">»</span>
<span class="sr-only">Next</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
the result i want is data on this image

Automatically calculating a ModelForm field on users click

I currently have a section in my form that looks like this:
With this form , I need to calculate Provisional Tax Date 1 and Provisional Tax Date 2 based on the Financial Year End Field ( Provisional Tax Date 1 must be 6 months after Financial Year End & Provisional Tax date 2 needs to be on the 31st of December on the year of the Financial Year End)
I would also need this to happen live, so as soon as the user changes the Financial Year End field it will update the other 2
If anyone has some sample code to assist with this, it would be highly appreciated.
Please see the below code from my project:
Views.py:
def newCompany(request):
form = CompanyForm()
if request.method == 'POST':
form = CompanyForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
print(form.errors)
content = {'form':form}
return render(request, 'main/newCompany.html', content)
Models.py
class CompanyClass(models.Model):
CompanyName = models.CharField(max_length=50 , blank=False)
RefNo = models.CharField(max_length=50 , blank=False )
FinancialYearEnd = models.DateField(auto_now=False, auto_now_add=False, null=False)
ProvisionalTaxDate1 = models.DateField(auto_now=False, auto_now_add=False)
ProvisionalTaxDate2 = models.DateField(auto_now=False, auto_now_add=False)
ARMonth = models.DateField(auto_now=False, auto_now_add=False)
checklist=models.ManyToManyField(Task)
def __str__(self):
return ( self.CompanyName)
Forms.py
class CompanyForm(ModelForm):
class Meta:
model = CompanyClass
fields = '__all__'
widgets = {
'FinancialYearEnd' : forms.SelectDateWidget,
'ProvisionalTaxDate1' : forms.SelectDateWidget,
'ProvisionalTaxDate2' : forms.SelectDateWidget,
'ARMonth' : forms.SelectDateWidget,
}
Template.html:
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
{% extends "main/base.html"%}
{% block content %}
<form class="form-group mt-4" action="" method="POST">
{% csrf_token %}
<h1 style="text-align: center "> New Company Customer </h1>
<br>
<div style="text-align: left; width: 100%; padding-left: 40px; padding-right: 60px">
<div class="row mb-3">
<div class="col">
<ul >
<li class='list-group-item ' style="background-color : #282828; color: white;">Company General Information</li>
<li class='list-group-item' style="border: 1px solid black;" style="border: 1px solid black;">Company Name {{ form.CompanyName }}</li>
<li class='list-group-item' style="border: 1px solid black;">Company Reference Number {{ form.RefNo }}</li>
<li class='list-group-item' style="border: 1px solid black;">Tax Registration Number {{ form.TaxRegNo }}</li>
<li class='list-group-item' style="border: 1px solid black;">Financial Year End {{ form.FinancialYearEnd }}</li>
<li class='list-group-item' style="border: 1px solid black;">AR Month {{ form.ARMonth }}</li>
<li class='list-group-item' style="border: 1px solid black;">Provisional Tax Date 1 {{ form.ProvisionalTaxDate1 }}</li>
<li class='list-group-item' style="border: 1px solid black;">Provisional Tax Date 2 {{ form.ProvisionalTaxDate2 }}</li>
</ul>
</div>
<div class="row mb-3">
<button type="submit" name="button" class="btn btn-primary "> Submit </button>
</div>
</div>
</form>
{% endblock %}

Why my paging bootstrap style does not work?

I practice "Flask Web Development"blog article when paging links paging,bootstrap style does not work.But the other can be used.I was using macros import, hope that other places can be common this.Is it necessary to add at import time? .
somebody help me.
this is index.html
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% import '_macros.html' as macros %}
{% block head %}
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% block scripts %}
{{ super() }}
<script type="text/javascript">
$('[data-spy="scroll"]').each(function () {
var $spy = $(this).scrollspy('refresh')
})
</script>
{% endblock %}
{% block styles %}
{{ super() }}
<style type="text/css">
body {
background-color: #ffffff;
/*background-color: #F0F0F0;*/
position: relative;
}
.header {
background-color: #FFFFFF;
background-attachment: scroll, fixed;
background-position: top left, top left;
background-repeat: repeat, no-repeat;
background-size: auto, auto 100%;
color: rgba(255, 255, 255, 0.5);
height: 100%;
left: 0;
padding: 8em 4em 0 0;
position: fixed;
text-align: right;
top: 0;
width: 20%;
padding: 0 0 0 0;
}
.img {
background-color: #235F2A;
height: 23.6076%;
width: 61.8%;
margin-top: 14.5924%;
margin-left: 19.1%;
margin-right: 19.1%;
padding: 0 0 0 0;
}
.breadcrumb {
margin-left: 25.28%;
margin-top: 3%;
width: 68.33%;
background-color: #FFFF93;
}
.sketcho {
width: 83.7%;
background-color: #ffffff;
opacity: 1;
margin-left: 7.72%;
margin-top: 8.5%;
}
.container-fluid {
margin-left: 20%;
padding-left: 0px;
padding-right: 0px;
}
.sketch {
width: 83.7%;
background-color: #ffffff;
opacity: 1;
margin-left: 7.72%;
margin-top: 1%;
}
section {
padding-left: 17px;
padding-right: 17px;
}
.paging {
margin-left: auto;
text-align: center
}
.center {
margin-top: 320px;
height: 35px;
}
.row_button {
width: 35px;
height: 35px;
float: left;
}
</style>
{% endblock %}
{% endblock %}
{% block title %}Index{% endblock %}
{% block page_content %}
<body id="top">
<div class="container-fluid">
{% for Article in Articles %}
<div class="row sketch">
<section id="one">
<header class="major">
{{ Article.head }}
</header>
<p>{{ Article.body }}</p>
<ul class="actions">
<li>
<button type="button" class="btn btn-info">Learn More</button>
</li>
</ul>
</div>
{% endfor %}
<div class="row paging">
{{ macros.pageination_widget(pageination, '.index') }}
</div>
</div>
<script src="{{ url_for('static',filename='js/jquery-3.2.1.min.js') }}"></script>
<script src="{{ url_for('static',filename='js/bootstrap.min.js') }}"></script>
</body>
{% endblock %}
_macros.html
{% macro pageination_widget(pageination, endpoint) %}
<nav aria-label="Page navigation">
<ul class="pageination">
<li {% if not pageination.has_prev %} class="disabled" {% endif %}>
<a href="{% if pageination.has_perv %}{{ url_for(endpoint, page=pageination.page - 1, **kwargs) }}{% else %}#{% endif %}">
«</a>
</li>
{% for page in pageination.iter_pages() %}
{% if page %}
{% if page == pageination.page %}
<li class="active">
{{ page }}
</li>
{% else %}
<li>{{ page }}</li>
{% endif %}
{% else %}
<li class="disabled"></li>
{% endif %}
{% endfor %}
<li {% if not pageination.has_next %} class="disabled" {% endif %}>
»
</li>
</ul>
</nav>
{% endmacro %}
It seems like you have a typo on your class names.
Try <ul class="pagination"> instead of <ul class="pageination">.
You can find the full docs for the classes to use here:
https://getbootstrap.com/docs/3.3/components/#pagination-default

How can i include a view function in django template?

I am new in django. So i need a help for including a view function within Template. I am searching but i am tired for finding my expectation. i want to use only django template tag. Would you please help me?
{View.py
def singUpLunch(request):
query_results = Menu.objects.all()
form=SingUpForm(request.POST or None)
if form.is_valid():
save_it=form.save(commit=False)
save_it.save()
messages.success(request,'Thanks for your co-operation')
return render_to_response('singUp.html',locals(),context_instance=RequestContext(request))
}
{my model
class SingUp(models.Model):
employee_id = models.AutoField(unique=True,primary_key=True)
name = models.CharField(max_length=20,choices=STATUS_CHOICES)
email = models.EmailField()
date = models.DateField()
lunch = models.BooleanField()
class Meta:
unique_together = ["name", "email","date"]
ordering = ['-date']
USERNAME_FIELD = 'employee_id'
REQUIRED_FIELDS = ['mobile']
def __unicode__(self):
return smart_unicode(self.email)
}
class SingUp(models.Model):
employee_id = models.AutoField(unique=True,primary_key=True)
name = models.CharField(max_length=20,choices=STATUS_CHOICES)
email = models.EmailField()
date = models.DateField() # auto_now_add=True, blank=True default=date.today(),blank=True
lunch = models.BooleanField()
class Meta:
unique_together = ["name", "email","date"]
ordering = ['-date']
USERNAME_FIELD = 'employee_id'
REQUIRED_FIELDS = ['mobile']
def __unicode__(self):
return smart_unicode(self.email)
my Template
{% load url from future %}
{% block content %}
{% if not email %}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Log in</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style>
body
{
margin: 0;
padding: 0;
color: #555;
font: normal 12pt Arial,Helvetica,sans-serif;
background:#ffffff url(check2.jpg) repeat-x;
width: 130%;
height: 100%;
position: fixed;
top: 40px;
left: 480px
}
.span3.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: #f5f5ff;
border: 1px solid #e3e3e3;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
}
</style>
</head>
<body>
<head><div class='page-header pagination-centered'><img src=/static/logo.png class='img-rounded pagination-centere' /></div> </head>
{{ state }}
<div class="span3 well" style="height: auto;margin-left: 1.7%;width: 30%;">
<h2>Please Login
New User: &nbsp<a href="/signup/">
SignUp</a></h2>
<div class="leftpane">
<form action="" method="post"> {% csrf_token %}
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
Email:
<input type="text" name="email" value="{{ email}}" /><br /><br />
password:
<input type="password" name="password" value="" /><br /><br />
<input type="submit" value="Log In" />
</form>
</div>
<div class="aboutus_portion">
</div>
</div>
<!-- <div id="rightcontent">
<li class=" dir"><h3>Admin</h3> </li>
</div>
-->
</body>
</html>
{% else %}
{% include 'singUpLunch' %} # here i want to call the view singUpLunch function
{% endif %}
{% endblock %}
You can see this Django custom template tags
Django expects template tags to live in a folder called 'templatetags' that is in an app module that is in your installed apps...
/my_project/
/my_app/
__init__.py
/templatetags/
__init__.py
my_tags.py
#my_tags.py
from django import template
register = template.Library()
#register.inclusion_tag('other_template.html')
def say_hello(takes_context=True):
return {'name' : 'John'}
#other_template.html
{% if request.user.is_anonymous %}
{# Our inclusion tag accepts a context, which gives us access to the request #}
<p>Hello, Guest.</p>
{% else %}
<p>Hello, {{ name }}.</p>
{% endif %}
#main_template.html
{% load my_tags %}
<p>Blah, blah, blah {% say_hello %}</p>
The inclusion tag renders another template, like you need, but without having to call a view function. Hope that gets you going.

First page blank when multiple pages rendered?

I use pisa for print from html to pdf. And I have a problem.
if amount of data few, than print in first page. if amount of data more, than he print in next page, but first page is empty.
What do you think about it?
Please help me
table {
-pdf-keep-with-next: true;
}
#page {
size: letter portrait;
margin-right: 30pt;
margin-left: 30pt;
}
#frame content_frame {
left: 50pt;
width: 512pt;
top: 50pt;
height: 692pt;
}
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pisa.CreatePDF(html.encode("UTF-8"), result, encoding='UTF-8', link_callback=self.fetch_resources)
response = HttpResponse(result.getvalue(), mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=report-%s-%s.pdf' % (start_date, end_date)
RequestContext(request)
<tbody>
<tr class="text-center">
<td>{% trans "Date" %}</td>
<td class="padding-top-5">
<p class="text-center"> {% trans "Journal" %} </p>
<p style="margin: 0 5pt;">{% trans "history, status, diagnosis and treatment for the treatment of recurrent disease" %}</p>
</td>
<td>{% trans "Doctor" %}</td>
</tr>
{% for reception in receptions %}
<tr>
<td class="text-center" style="width: 30%; vertical-align: top">
<p class="separator"> </p>
{{ reception.date_created|date:"d F Y" }}
</td>
<td>
<div style="padding: 5px">
{% if reception.result|length_is:0 or reception.result == None %}
{% else %}
{{ reception.result|linebreaks }}
{% endif %}
</div>
<td style="vertical-align: top; width: 30%">
<p class="separator"> </p>
{{ reception.doctor.doctor_name }}
</td>
</tr>
{% endfor %}
</tbody>
</table>

Categories