Too Many Values To Unpack While Rendering Data On A Template (Django) - python

VIEWS
def Aeging(request):
current_date_thirty = date.today().isoformat()
days_before_thirty = (date.today() - timedelta(days=30)).isoformat()
thirty = journalVoucher.objects.values('account_name_one').order_by('account_name_one').filter(voucher_date_one__range=[days_before_thirty,current_date_thirty]).annotate(outstanding=(Sum('credit_amount_one')-Sum('debit_amount_one')))
for item in thirty:
item['account_name_one'] = CreateLedger.objects.get(id=item['account_name_one'])
return thirty
context ={'thirty':thirty}
return render(request,'report/aeging/aeging_analysis.html',context)
<div class="row">
<div class="table-responsive col-md-6">
<table id="example" class="table table-bordered">
<caption style="caption-side:top; text-align: center;"><h3>0-30 Days</h3></caption>
<thead class="thead-dark">
<tr>
{# <th>S No.</th>#}
<th>Party Name</th>
<th>Total Amount</th>
</tr>
</thead>
<tbody>
{% for item in thirty %}
<tr class="table-success">
{# <td>{{ }} </td>#}
<td>{{item.account_name_one}}</td>
<td>{{ item.outstanding }} </td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr class="totalColumn">
<td style="visibility:hidden;"></td>
<td>Total:</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
Hi The Query Is perfectly Run on python shell but when i render the data on a template it shows too many values to unpack (expected 2).
I Provide You My Views and Template Code.
Any Solution Of This??
Images Link..
https://drive.google.com/drive/folders/1V7uI4YS4Qg8ng4bmN0aCFvp85Dzi8n5S?usp=sharing

Related

How to pass a variable to a flask app route through a html button

I am trying to create a page where it shows records from the database and shows a delete button next to them. One of the elements shown is the variable needed for the delete function my problem is that I do not know how to get and pass that variable for the route that deletes the record from the database.
routes.py
#app.route("/deletetraining",methods=['GET', 'POST'])
def deleteTraining():
return render_template('deleteTraining.html', trainings = getAllTrainings(), title = 'Delete')
#app.route("/delete")
def delete(tid):
deleteTrainingByID(tid)
return redirect(url_for('deleteTraining'))
deleteTraining.html
{% extends 'layout.html' %}
{% block content %}
<h1 class="text-muted">All Trainings</h1>
<table class="table" >
<thead>
<tr>
<th scope="col">TID</th>
<th scope="col">Workplan</th>
<th scope="col">Cost Centre Code</th>
<th scope="col">Objective</th>
<th scope="col">Name</th>
<th scope="col">Location</th>
<th scope="col">Start Date</th>
<th scope="col">End Date</th>
<th scope="col">Hours</th>
<th scope="col">Days</th>
<th scope="col">Gender Hours</th>
<th scope="col">For MEL</th>
</tr>
</thead>
<tbody>
{% for training in trainings %}
<tr>
{% for element in training %}
<td>{{element}}</td>
{% endfor %}
<td>
<a class="btn btn-danger" type="button" href="/delete">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
In the template you must pass the id in the delete training button
<a class="btn btn-danger" type="button" href="/delete/{{training.id}}">Delete</a>
And in your #app.route you must add
#app.route("/delete/<tid>")

'post' object is not iterable in django and it is showing error but i'm not getting what's going wrong on code

TypeError at /dashboard
'post' object is not iterable i am just try to get data from db table and show on dashboard in dabel form
my dashboard.html page
{% if posts %}
<table class="table table-dark table-hover">
<thead>
<tr>
<th scope="col" style="width:3%">ID</th>
<th scope="col" style="width:30%">Title</th>
<th scope="col" style="width:55%">Description</th>
<th scope="col" style="width:15%">Action</th>
</tr>
</thead>
<tbody>
{% for post in posts %}
<tr>
<td>{{posts.id}} </td>
<td>{{posts.title}}</td>
<td>{{posts.desc}}</td>
<td><a class="btn btn-primary" type="submit" value="Submit">Edit</a>
<form action ='' , method ='POST' class='d-inline'>
{% csrf_token %}
<input type='submit' class='btn btn-danger btn-sm' value ='Delete' >
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<h4 class =' text-center alert alert-warning'>No Records </h4>
{% endif %}
</div>
</div>
{% endblock content %}
my views.py
def dashboard(request):
if request.user.is_authenticated:
posts= post.objects.all()
return render(request,'dashboard.html',{'posts':post})
else:
return HttpResponseRedirect('login')
urls.py
path('dashboard',views.dashboard,name='dashboard'),
You have a typo in your views.py file. Try change this:
return render(request,'dashboard.html',{'posts':post})
to this:
return render(request,'dashboard.html',{'posts':posts})
I assume in template dashboard.html you have to change this :
{% for post in posts %}
<tr>
<td>{{posts.id}} </td>
<td>{{posts.title}}</td>
<td>{{posts.desc}}</td>
to this :
{% for post in posts %}
<tr>
<td>{{post.id}} </td>
<td>{{post.title}}</td>
<td>{{post.desc}}</td>
It should be like this:
{% for post in posts %}
<tr>
<td>{{post.id}} </td>
<td>{{post.title}}</td>
<td>{{post.desc}}</td>

How can I make actions with selected objects in Django

I'm new at Django and have some troubles with making actions with database objects, which I need to select with checkboxes.
models.py
class Scooter (models.Model):
name = models.CharField(max_length=100, verbose_name='name')
price = models.IntegerField(max_length=10, verbose_name='price')
url = models.URLField(verbose_name='url')
views.py
class MainView(TemplateView):
template_name = 'mainApp/index.html'
def get(self, request):
scooters = Scooter.objects.all().order_by('price')
return (render(request, self.template_name, context={'scooters':scooters}))
and my html template is:
<table class="table table-sm table-borderless table-hover table-responsive-lg">
<caption>Перечень товаров</caption>
<thead class="thead-dark">
<tr>
<th scope="col"></th>
<th scope="col">№</th>
<th scope="col">Name</th>
<th scope="col">Price</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<form action="" method="post">
{% for elem in scooters %}
<tr>
<th>
<input type="checkbox" id="{{ elem.num }}" name="scooter_select" value="/{{ elem.num }}">
<label for="scooter{{ elem.num }}"></label>
</th>
<th>
{{ forloop.counter }}
</th>
<th scope="row">
{{ elem.name }}
</th>
<td>{{ elem.price }}</td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
{% endfor %}
</form>
</tbody>
</table>
So I can't understand, how can I catch selected with checkbox objects?

Separate the values in dictionary into two column. Python and Django

I've a program which will read data from text file.
There are 3 types of data that I need to read from text file.
visual id
time
tname_pb
Problem
I have 3 columns and need to separate output into different columns.
But, visual id is working perfectly, but time and tname_pb are combined together.
Question
How can I separate time and tname_pb into two different column.
Current views.py based on the picture
with open(path) as input_data:
for line in input_data:
if line.startswith('2_visualid_'):
visual_key = line.lstrip('2_visualid_').rstrip()
data.update({visual_key: []})
if 'time' in tokens:
if search_time in line and visual_key in data:
data[visual_key].append(next(input_data).lstrip('2_mrslt_').rstrip())
if 'tname_pb' in tokens:
if tname_pb in line and visual_key in data:
data[visual_key].append(next(input_data).lstrip('2_mrslt_').rstrip())
Current template based on the picture
<div class="input-group" align="center" style=" left:10px; top:-110px; width:99%">
<table class="table table-bordered">
<thead class="success" >
<tr>
<th class="success">
<b>Visual ID</b>
</th>
<th class="success">
<b>Time Delay Index</b>
</th>
<th class="success">
<b>Tname PB</b>
</th>
</tr>
{% for key, values in output.items %}
<tr class="">
<td rowspan={{ values|length|add:1 }}><b>{{ key }}</b></td>
{% for value in values %}
<tr class="">
<td ><b>{{value}}</b></td>
</tr>
{% endfor %}
</tr>
{% endfor %}
</thead>
</table>
</div>
NOTE
I have tried few examples from Google, but I get errors with them.
I will post them here if they help clarify my question. I left them out because I don't want my question to be confusing.
You have a new table row going on here for each value.
{% for value in values %}
<tr class="">
<td><b>{{value}}</b></td>
</tr>
{% endfor %}
Instead of this, you need to make a new table cell for each value.
<table class="table table-bordered">
<thead class="success">
<tr>
<th class="success">
Visual ID
</th>
<th class="success">
Time Delay Index
</th>
<th class="success">
Tname PB
</th>
</tr>
</thead>
<tbody>
{% for key, values in output.items %}
<tr class="">
<td><b>{{ key }}</b></td>
{% for value in values %}
<td><b>{{ value }}</b></td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>

Printing page numbers using Pisa

I am using pisa in my django project, to make my html generate on a PDF for report functionality. Some of my reports are getting rather large and I have noticed it doesn't have any page numbering on it. Does anyone know how I can get page numbers to show up on the printed PDF report?
edit
here is how I generate the PDF
if request.POST.has_key('print_report_submit'):
context['show_report'] = True
context['mb_logo'] = os.path.join(os.path.dirname(__file__), "../../../media/images/mb_logo.jpg")
html = render_to_string('reports/fam_maturity_print.html', RequestContext(request,context))
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
response = HttpResponse(result.getvalue(), mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=family_maturity-statement.pdf'
return response
HTML
{% if show_report %}
<table width="100%">
<tr>
<td colspan="2" align="center" width="400px">
<h1 class="title">Family Maturities by Year</h1>
<br/><br/>
</td>
</tr>
<tr>
<td width="500px">
<img src="{{ mb_logo }}"/>
<td> <p>
<img style="max-height: 60px; max-width:60px;" src="{{ check_image }}"/>
</p>
</tr>
</table>
<br/>
<br/>
<hr class="report_hr1"/>
<h2 class="state_head" style="font-size: 16px;">Statement Information As of {{ statement_date|date:"F d, Y" }}</h2>
<hr class="report_hr1"/>
<table>
{% for plan_dict in plan_list %}
<hr class="report_hr2"/>
<table>
<tr>
<td><strong>Plan Holder: </strong></td><td>{{ plan_dict.plan.get_primary_owner.member.client}}</td>
<td><strong>Joint Owner(s): </strong></td>
<td>
{% for member in plan_dict.plan.planmember_set.all %}
{% ifnotequal member.ownership_type.code "primary" %}
{{ member }}
{% endifnotequal %}
{% endfor %}
</td>
</tr>
<tr>
<td><strong>Plan ID: </strong></td><td>{{ plan_dict.plan.id }}</td>
</tr>
<tr>
<td><strong>Plan type: </strong></td><td>{{ plan_dict.plan.plan_type }}</td>
</tr>
</table>
<hr class="report_hr2"/>
{# This is the table for the current year's maturities #}
{% if plan_dict.investment %}
<table>
<td colspan="2"><h3>{{ cur_year }}</h3></td>
<tr>
<th>Financial Institution</th>
<th>Type</th>
<th>Principal</th>
<th>Maturity</th>
</tr>
{% for i in plan_dict.investment %}
<tr>
<td>{{ i.financial_institution.abbr }}</td>
<td>{{ i.product.code }}</td>
<td>${{ i.amount|intcomma }}</td>
<td>${{ i.maturity_amount|intcomma }}</td>
</tr>
{% endfor %}
<tr>
<td><strong>Total for {{ cur_year }}</strong></td>
<td></td>
<td><strong>${{ plan_dict.total|intcomma }}</strong></td>
<td><strong>${{ plan_dict.total_m|intcomma }}</strong></td>
</tr>
</table>
{% endif %}
<div id="holding_table" align="center">
<h3>Holding Totals with Each Company</h3>
<table>
<tr>
<td style="font-weight: bold;">Financial Institution</td>
<td style="font-weight: bold;">Total</td>
</tr>
{% for l in plan_dict.total_list %}
{% if l.maturity_amount__sum != None %}
<tr>
<td>{{ l.financial_institution__abbr }}</td>
<td>${{ l.maturity_amount__sum|intcomma }}</td>
</tr>
{% endif %}
{% endfor %}
<tr>
<td style="font-weight: bold;">Total Non-Fund Holdings for this plan</td>
<td style="font-weight: bold;">${{ plan_dict.grand|intcomma }}</td>
</tr>
</table>
<span class="disclaimer_span">This report has been prepared from data believed to be reliable but no
representation is made as to accuracy or completeness.</span>
</div>
<br/>
<br/>
{% endfor %}
</table>
{% endif %}
Any help would be much appreciated.
How says in this link:
http://www.arnebrodowski.de/blog/501-Pisa-and-Reportlab-pitfalls.html
One problem I ran into was adding a static footer to my pages, which contains a <pdf:pagenumber /> tag and should show the current pagenumber at the bottom of every page of the resulting PDF. The problem was, that every page just showed the number 0. The solution was very simple, but I was only able to figure it out after studiying the pisa source-code: You can only use the tag inside a paragraph, not (as I did) inside a table for example. Even parapgraphs inside tables don't work. It has to be a top-level paragraph.
Edit
Try this:
<div>
<pdf:pagenumber />
</div>
This is working for me you need to use this its for A3 size
#page{
size: A3;
margin: 1cm;
#frame footer_frame { /* Another static Frame */
-pdf-frame-content: footer_content;
left: 400pt; top: 1170pt; height: 20pt;
}
}
you have to put on above table
<div id="footer_content"> Page <pdf:pagenumber>
of <pdf:pagecount> </div>

Categories

Resources