What I would like the following code to do is separate rendering of a page and the modals generated within it, the goal is a generic table framework based in Bootstrap in which I can put cells of different types, text, links, or buttons. I populate a basic table in app.py and then have a separate method in the same module I would use to create a modal that would pop up in the same window as the main one. The MWE consists of two functions in the python module and two separate HTML files.
I know it won't work as is because there's nothing to connect to gen_modal, but I'm not sure what I would need to put where to connect this together. Any thoughts?
app.py:
#bp.route('/view_table_test')
#login_required
def modal_test():
columns = [{'name':'column_a', 'display-name':'Column A', 'type':'text'},
{'name':'column_b', 'display-name':'Column B', 'type':'text'},
{'name':'column_c', 'display-name':'Column C', 'type':'text'},
{'name':'column_d', 'display-name':'Column D (Links)', 'type':'link'},
{'name':'column_e', 'display-name':'Column E (Buttons)', 'type':'button'}]
data = []
for i in range(10):
datum = {}
datum['column_a'] = {'text':'Text A' + str(i), 'link':None}
datum['column_b'] = {'text':'Text B' + str(i), 'link':None}
datum['column_c'] = {'text':'Text C' + str(i), 'link':None}
datum['column_d'] = {'text':'Link D' + str(i), 'link':'link_a'+str(i)}
datum['column_e'] = {'text':'Button E' + str(i), 'data-target':'#data_target_'+str(i)}
data.append(datum)
return render_template('view_table_test.html',
title="View Test Columns",
columns=columns,
data=data)
#bp.route('/<int:id>/gen_modal', methods=('GET', 'POST'))
def gen_modal(id):
data_target = 'data_target_'+str(id)
text = 'Modal Panel For ID ' + str(id)
return render_template('gen_modal.html',
data_target=data_target,
text=text)
view_table_test.html:
{% block header %}
<h1>{% block title %}{{ title }}{% endblock %}</h1>
{% endblock %}
{% block content %}
<table id="table">
<thead>
<tr>
{% for column in columns %}
<th data-field="{{ column['name'] }}"
data-filter-control="select"
data-filter-control-visible="true"
data-sortable="true">{{ column['display-name'] }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in data %}
<tr>
{% for column in columns %}
{% if column['type']=="link" %}
<td>{{ row[column['name']]['text'] }}</td>
{% elif column['type']=="button" %}
<td><button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="{{ row[column['name']]['data-target'] }}">{{ row[column['name']]['text'] }}</button></td>
{% else %}
<td>{{ row[column['name']]['text'] }}</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
gen_modal.html:
<!doctype html>
<!-- Modal -->
<div class="modal fade" id="{{ data_target }}" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">{{ text }}</h4>
</div>
<div class="modal-body">
<p>Modal Stuff</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Here is the visual output. The buttons don't work.
Related
I am currently running into the above error when trying to access my reportsHome page. It seems to be a problem with the 'HREF' section of the form where the code is href="{% url 'printReports' reports_pk %}"
The templates , views and URLs are listed in the below code:
reportsHome.html :
{% block content%}
<h1 style=" text-align: center">Reports</h1>
<hr>
<br>
<div class="list-group">
<a href="#" class='list-group-item active'>Print Single Complex's</a>
{% for x in model %}
<a href="{% url 'printReports' reports_pk %}" class="list-group-item list-group-item-action" >{{ x.Complex }} Reports</a>
{% endfor %}
</div>
{% endblock %}
printPDF.html :
<title>PDF Outuput - TrialBalance</title>
{% block content%}
<h1 class = 'center'>Kyle Database Trial Balance</h1>
<br>
</div>
<br>
<br>
<div class="table-container">
<table style="width: 100%">
<th >Account</th>
<th>Description</th>
<th>Debit</th>
<th>Credit</th>
{% for arr_trbYTD in arr_trbYTD %}
<tr>
<td>{{ arr_trbYTD.Description }}</td>
<td>{{ arr_trbYTD.Account }}</td>
<td>
{%if arr_trbYTD.Debit > 0%}
{{arr_trbYTD.Debit}}
{%endif%}
</td>
<td>
{%if arr_trbYTD.Credit > 0%}
{{arr_trbYTD.Credit}}
{%endif%}
</td>
</tr>
<tr >
{% endfor %}
<td> <b>Totals</b> </td>
<td> </td>
{% for xDebitTotal in xDebitTotal %}
<td><b>R {{ xDebitTotal }}</b></td>
{% endfor %}
{% for xCreditTotal in xCreditTotal %}
<td><b>R {{ xCreditTotal }}</b></td>
{% endfor %}
</tr>
</table>
</div>
<br>
<br>
<br>
{% endblock %}
Views.py :
def printReports(request , reports_pk):
pkForm = get_object_or_404(SettingsClass , pk=reports_pk)
form= SettingsClass(instance=pkForm)
complexName = form.Complex
printTrialBalance = True
includeOpeningBalance = ''
useMainAccounts = 'len(Master_Sub_Account) < 5 '
printNullValues = '' # else it will print null values
printDescription = '' # if false it wil remove the print description line
printAccount = '' # if false it wil remove the print account line
OrderByAccount = 'ORDER BY iAccountType '
#CHECKING TRIAL BALANCE SETTINGS
if form.Trial_balance_Year_to_date == True:
printTrialBalance = True
baseTRBYear = 'Inner JOIN [?].[dbo].[Accounts] '\
'on Accounts.AccountLink = genLedger.AccountLink '\
'Inner JOIN [?].[dbo].[_etblGLAccountTypes] as AccountTypes '\
'on Accounts.iAccountType = AccountTypes.idGLAccountType '\
'WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122) '\
'AND genLedger.TxDate > ?'\
### Printing Trial Balance PDF
response = HttpResponse(content_type= 'application/pdf')
response['Content-Disposition']= 'attachment; filename=TrialBalance' + \
str(datetime.now()) + '.pdf'
response['Content-Transfer-Encoding'] = 'binary'
#SQL STATEMENT
xtrbYTD = baseSelect + trbYTD + op1 + op2 + op3 + op6
cursor = cnxn.cursor();
cursor.execute(baseTRBYear, [complexName], [complexName], [complexName], [one_yrs_ago]);
xAll = cursor.fetchall()
cursor.close()
xtrbYTD = []
for row in xtrbYTD:
rdict = {}
rdict["Description"] = row[0]
rdict["Account"] = row[1]
rdict["Debit"] = row[2]
rdict["Credit"] = row[3]
arr_trbYTD.append(rdict)
content = {"arr_trbYTD":arr_trbYTD , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal , 'complexName':complexName , 'openingBalances': openingBalances ,'printZero':printZero}
html_string=render_to_string('main/pdf-trialbalance.html' , content)
html=HTML(string=html_string)
result=html.write_pdf()
with tempfile.NamedTemporaryFile(delete=True) as output:
output.write(result)
output.flush()
output.seek(0)
response.write(output.read())
return response
else:
printTrialBalance = False
return render(request , 'main/printReports.html')
URLS.PY:
#Reports
path('reportsHome' , views.reportsHome, name='reportsHome'),
path('accConnect/printReports/<int:reports_pk>' , views.printReports , name='printReports')
]
If anyone knows what could be causing this error , please assist
if 'model' represents your model and x element of your model then you can access the primary key using x.pk
{% block content%}
<h1 style=" text-align: center">Reports</h1>
<hr>
<br>
<div class="list-group">
<a href="#" class='list-group-item active'>Print Single Complex</a>
{% for x in model %}
<a href="{% url 'printReports' x.pk %}" class="list-group-item list-group-item-action" >{{ x.Complex }} Reports</a>
{% endfor %}
</div>
{% endblock %}
I am assuming that reports_pk is in your model so i am editing accoring it hope it works as my understanding
{% block content%}
<h1 style=" text-align: center">Reports</h1>
<hr>
<br>
<div class="list-group">
<a href="#" class='list-group-item active'>Print Single Complex's</a>
{% for x in model %}
<a href="{% url 'printReports' /{{reports_pk}} %}" class="list-group-item list-group-item-action" >{{ x.Complex }} Reports</a>
{% endfor %}
</div>
{% endblock %}
I am trying to create a edit form to update the database using Django model Forms but the problem is that edit form part of the sizeProductMap.html page is not rendering when edit form (sizeProductMap_edit) request is made.
My models are as shown below.
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
def __str__(self):
return "{}-->{}".format(self.prod_ID,
self.prod_Name)
class Size(models.Model):
size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
prod_size = models.CharField("Product Size", max_length=20, null=False)
def __str__(self):
return "{size_id}-->{prod_size}".format(size_id=self.size_id,
prod_size=self.prod_size)
class SizeProductMapping(models.Model):
size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True)
size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
def __str__(self):
return ".`. {}_____{}".format(self.size_id,
self.prod_id)
This is the form I used to add and edit the model.
forms.py
from django import forms
from user.models import SizeProductMapping
class SizeProductMapForm(forms.ModelForm):
class Meta:
model = SizeProductMapping
fields = ['size_id', 'prod_id']
Here is the view I created to add ,update and delete the record.
views.py
def sizeProductMap(request):
form = SizeProductMapForm(request.POST, request.FILES)
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect("/admin1/sizeProductMap/")
else:
sizeProductMap_show = SizeProductMapping.objects.all()
# start paginator logic
paginator = Paginator(sizeProductMap_show, 3)
page = request.GET.get('page')
try:
sizeProductMap_show = paginator.page(page)
except PageNotAnInteger:
sizeProductMap_show = paginator.page(1)
except EmptyPage:
sizeProductMap_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/sizeProductMap.html', {'sizeProductMap_show': sizeProductMap_show, 'form': form})
def sizeProductMap_delete(request, id):
sizeProductMap_delete = SizeProductMapping.objects.filter(size_p_map_id=id)
sizeProductMap_delete.delete()
return redirect('/admin1/productSizeMap')
def sizeProductMap_edit(request, id):
instance = SizeProductMapping.objects.get(size_p_map_id=id)
form = SizeProductMapForm(instance=instance)
if request.method == 'POST':
form = SizeProductMapForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('/admin1/sizeProductMap')
return render(request, 'admin1/sizeProductMap.html', {'form': form})
This is my urls.
urls.py
from django.urls import path
from admin1 import views
urlpatterns = [
path('sizeProductMap/', views.sizeProductMap, name="admin-size-product-map"),
path('sizeProductMap_delete/<int:id>', views.sizeProductMap_delete, name="admin-size-product-map-delete"),
path('sizeProductMap_edit/<int:id>', views.sizeProductMap_edit, name="admin-size-product-map-edit"),
]
This is the Html page where I want to display the form according to the page request.
sizeProductMap.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Size Product Map{% endblock %}
{% block main %}
<h1>
<center>Size Product Map</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
{% if sizeProductMap_show %}
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Size Product Mapping
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Size Product Mapping</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-size-product-map'%}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.size_id.label_tag}}
</th>
<td>{{form.size_id}}</td>
</tr>
<tr>
<th>
{{form.prod_id.label_tag}}
</th>
<td>
{{form.prod_id}}
</td>
</tr>
</table>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Size Product Map Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Size Product Mapping Id</th>
<th>Product ID</th>
<th>Size ID</th>
<th>Action</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in sizeProductMap_show %}
<tr>
<td>{{x.size_p_map_id}}</td>
<td>{{x.prod_id}}</td>
<td>{{x.size_id}}</td>
<td><a href="{% url 'admin-size-product-map-edit' x.size_p_map_id %}"
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="{% url 'admin-size-product-map-delete' x.size_p_map_id %}"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if sizeProductMap_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{sizeProductMap_show.previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in sizeProductMap_show.paginator.page_range %}
{% if sizeProductMap_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if sizeProductMap_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{sizeProductMap_show.next_page_number}}">
Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{% endif %}
{% if sizeProductMap_edit %}
<form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
{% csrf_token %}
{{form.size_id}}
{{form.prod_id}}
</form>
{% endif %}
</div>
</div>
</div>
{% endblock %}
And if it is possible to reduce the number of line of code please also help. Thanks in advance.
I've found out the answer. There was a really a silly mistake by me.
In the sizeProductMap.html there is a mistake let me point out that:
sizeProductMap.html
{% if sizeProductMap_edit %}
<form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
{% csrf_token %}
{{form.size_id}}
{{form.prod_id}}
</form>
{% endif %}
Here I am checking for instance {% if sizeProductMap_edit %} this is the wrong thing.
I have to check {% if instance %} according to my views.py.
In my flask-admin index_view, I am displaying financial information for my rows.
I would like to add an extra row, "summary row", at the bottom of my index_view table which sums up all the columns.
How can I accomplish this?
There's a couple of things you need to do. Provide a custom list.html template and override the render() method for the view. In the render method inject your summary data into the kwargs and in the custom template use the summary data to output appropriate html. You could add the summary data to the end of the existing data table or add it to a separate table, as seen in the example below.
Here's a self-contained example (two files) using Flask-Admin 1.5, SQLAlchemy and SQLite. custom_list.html is taken directly from flask-admin list.html and we are manipulating the block beginning at line 68:
{% block model_list_table %}
...
{% endblock %}
Note that in the render() method the summary data is an array of dicts. Each dict has a 'title' attribute (e.g 'title: 'Page Total' plus an attribute for each of the columns summary data is required.
app.py
import random
import string
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin.contrib.sqla import ModelView
from flask_admin import Admin, expose
# Create application
from sqlalchemy import func
app = Flask(__name__)
# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] = '123456790'
# Create in-memory database
app.config['DATABASE_FILE'] = 'sample_db.sqlite'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE_FILE']
db = SQLAlchemy(app)
# Flask views
#app.route('/')
def index():
return 'Click me to get to Admin!'
class Project(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), nullable=False, unique=True)
cost = db.Column(db.Integer(), nullable=False)
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return "Name: {name}; Cost : {cost}".format(name=self.name, cost=self.cost)
class ProjectView(ModelView):
# don't call the custom page list.html as you'll get a recursive call
list_template = 'admin/model/custom_list.html'
form_columns = ('name', 'cost')
page_size = 5
def page_cost(self, current_page):
# this should take into account any filters/search inplace
_query = self.session.query(Project).limit(self.page_size).offset(current_page * self.page_size)
return sum([p.cost for p in _query])
def total_cost(self):
# this should take into account any filters/search inplace
return self.session.query(func.sum(Project.cost)).scalar()
def render(self, template, **kwargs):
# we are only interested in the list page
if template == 'admin/model/custom_list.html':
# append a summary_data dictionary into kwargs
_current_page = kwargs['page']
kwargs['summary_data'] = [
{'title': 'Page Total', 'name': None, 'cost': self.page_cost(_current_page)},
{'title': 'Grand Total', 'name': None, 'cost': self.total_cost()},
]
return super(ProjectView, self).render(template, **kwargs)
admin = Admin(app, template_mode="bootstrap3")
admin.add_view(ProjectView(Project, db.session))
def build_sample_db():
db.drop_all()
db.create_all()
for _ in range(0, 100):
_cost = random.randrange(1, 1000)
_project = Project(
name=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)),
cost=_cost
)
db.session.add(_project)
db.session.commit()
if __name__ == '__main__':
build_sample_db()
app.run(port=5000, debug=True)
templates/admin/model/custom_list.html
{% extends 'admin/model/list.html' %}
{% block model_list_table %}
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover model-list">
<thead>
<tr>
{% block list_header scoped %}
{% if actions %}
<th class="list-checkbox-column">
<input type="checkbox" name="rowtoggle" class="action-rowtoggle" title="{{ _gettext('Select all records') }}" />
</th>
{% endif %}
{% block list_row_actions_header %}
{% if admin_view.column_display_actions %}
<th class="col-md-1"> </th>
{% endif %}
{% endblock %}
{% for c, name in list_columns %}
{% set column = loop.index0 %}
<th class="column-header col-{{c}}">
{% if admin_view.is_sortable(c) %}
{% if sort_column == column %}
<a href="{{ sort_url(column, True) }}" title="{{ _gettext('Sort by %(name)s', name=name) }}">
{{ name }}
{% if sort_desc %}
<span class="fa fa-chevron-up glyphicon glyphicon-chevron-up"></span>
{% else %}
<span class="fa fa-chevron-down glyphicon glyphicon-chevron-down"></span>
{% endif %}
</a>
{% else %}
{{ name }}
{% endif %}
{% else %}
{{ name }}
{% endif %}
{% if admin_view.column_descriptions.get(c) %}
<a class="fa fa-question-circle glyphicon glyphicon-question-sign"
title="{{ admin_view.column_descriptions[c] }}"
href="javascript:void(0)" data-role="tooltip"
></a>
{% endif %}
</th>
{% endfor %}
{% endblock %}
</tr>
</thead>
{% for row in data %}
<tr>
{% block list_row scoped %}
{% if actions %}
<td>
<input type="checkbox" name="rowid" class="action-checkbox" value="{{ get_pk_value(row) }}" title="{{ _gettext('Select record') }}" />
</td>
{% endif %}
{% block list_row_actions_column scoped %}
{% if admin_view.column_display_actions %}
<td class="list-buttons-column">
{% block list_row_actions scoped %}
{% for action in list_row_actions %}
{{ action.render_ctx(get_pk_value(row), row) }}
{% endfor %}
{% endblock %}
</td>
{%- endif -%}
{% endblock %}
{% for c, name in list_columns %}
<td class="col-{{c}}">
{% if admin_view.is_editable(c) %}
{% set form = list_forms[get_pk_value(row)] %}
{% if form.csrf_token %}
{{ form[c](pk=get_pk_value(row), display_value=get_value(row, c), csrf=form.csrf_token._value()) }}
{% else %}
{{ form[c](pk=get_pk_value(row), display_value=get_value(row, c)) }}
{% endif %}
{% else %}
{{ get_value(row, c) }}
{% endif %}
</td>
{% endfor %}
{% endblock %}
</tr>
{% else %}
<tr>
<td colspan="999">
{% block empty_list_message %}
<div class="text-center">
{{ admin_view.get_empty_list_message() }}
</div>
{% endblock %}
</td>
</tr>
{% endfor %}
</table>
</div>
<h3>Summaries</h3>
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover model-list">
<thead>
<tr>
{% if actions %}
<th class="list-checkbox-column">
</th>
{% endif %}
<th class="col-md-1"></th>
{% for c, name in list_columns %}
{% set column = loop.index0 %}
<th class="column-header col-{{c}}">
{{ name }}
</th>
{% endfor %}
</tr>
</thead>
{% for row in summary_data %}
<tr>
<td colspan="2"><strong>{{ row['title'] or ''}}</strong></td>
{% for c, name in list_columns %}
<td class="col-{{c}}">
{{ row[c] or ''}}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</div>
{% block list_pager %}
{% if num_pages is not none %}
{{ lib.pager(page, num_pages, pager_url) }}
{% else %}
{{ lib.simple_pager(page, data|length == page_size, pager_url) }}
{% endif %}
{% endblock %}
{% endblock %}
I am covering HTML to PDF file using weasyprint in Django web app. Everything is working fine but It is working is very slow when converting HTML to PDF. It takes more than two minutes long When I convert it.
I am using Bangla font in my HTML file.
this is my views.py code
def get_pdf_file(request, customer_id, sys_type):
sys_type = customer_id
area = "pdf"
site_credit = site_credit1
time_now = timezone.now()
customers = get_object_or_404(CustomerInfo, pk=customer_id)
due_taka_track = customers.duetaka_set.all()
if due_taka_track == None:
due_taka_track = 0
unpaid_taka = int(customers.customer_price -
customers.customer_due_taka_info)
due_taka_track = customers.duetaka_set.all()
sum_cost_taka = due_taka_track.aggregate(
sp=Sum('customer_due')).get('sp', 0)
if sum_cost_taka == None:
sum_cost_taka = 0
total_paid_taka = sum_cost_taka + customers.customer_due_taka_info
payment_status = 'complete'
payment_message = 'Full Paid'
remain_taka='PAID'
remain_msg=''
if customers.customer_due_taka_info < customers.customer_price:
payment_status = 'incomplete'
payment_message = 'সম্পূর্ন টাকা পরিষোধ করা হয়নি'
remain_msg='টাকা বাকী আছে'
baki_ase="পাওনা আছে "
remain_taka = customers.customer_price - customers.customer_due_taka_info
context = {'customers': customers,
'sys_type': sys_type,
'area': area,
'site_credit': site_credit,
'site_name': 'Moon Telecom',
'sys_type': sys_type,
'due_taka_track': due_taka_track,
'total_paid_taka': total_paid_taka,
'payment_message': payment_message,
'time_now': time_now,
'unpaid_taka': unpaid_taka,
'payment_message': payment_message,
'remain_taka': remain_taka,
'sum_cost_taka': sum_cost_taka,
'remain_msg': remain_msg}
html_string = render_to_string('shop/pdf_invoice.html', context)
html = HTML(string=html_string)
result = html.write_pdf()
response = HttpResponse(content_type='application/pdf;')
response['Content-Disposition'] = 'inline; filename=invoice'+sys_type+'.pdf'
response['Content-Transfer-Encoding'] = 'UTF-8'
with tempfile.NamedTemporaryFile(delete=True) as output:
output.write(result)
output.flush()
output = open(output.name, 'rb')
response.write(output.read())
return response
This is my HTML file. This file I am convering HTML to PDF
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Moon Telecom</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://fonts.maateen.me/kalpurush/font.css" rel="stylesheet">
<style>
p,
td,
tr {
font-size: 10px;
line-height: 12px;
}
body {
font-family: 'Kalpurush', Arial, sans-serif !important;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="site_title" style="text-align:center; margin:0 auto">
<p style="font-size:15px">মুন টেলিকম</p>
<div class="invoice_info_one" style="width:100%; text-align:center">
<p>সকল প্রকার মোবাইল সেট, সীম কার্ড, মেমোরী কার্ড, MP-3, সোলার চার্জার, সোলার ফ্যান, মোবাইল ফোনের ব্যাটারী,
চার্জার, ক্যাচিং,কাভার,হেডফোন, রেবন, ডিসপ্লে এবং ইলেট্রিক মালামাল বিক্রেতা</p>
</div>
<div class="invoice_location">
<p>জাহাঙ্গীর সুপার মার্কেট, ব্রীজ রোড, ফুলহাতা বাজার, মোডেলগঞ্জ।</p>
</div>
<div class="invoice_contact">
<p>01717-051200(সুকান্ত) 01828-163858(দোকান)</p>
<p>
<b>Email:</b> moontelecom2008#gmail.com</p>
</div>
<hr>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="customer_info">
{% if customers.customer_name %}
<p style="font-size:15px">Customer Name:
<b> {{customers.customer_name}}</b>
<span style="color:red">{{customers.customer_first_due_info}}</span>
</p>
{% else %}
<p> Name: দেওয়া হয়নি</p> {% endif %}
<p style="font-size:14px">Phone Number: {% if customers.customer_mobile_no %} {{customers.customer_mobile_no}} {% else %} No Mobile
Number {% endif %}
</p>
<p style="font-size:14px">Purchase Time: {{customers.customer_sell_date}}</p>
<p style="font-size:14px">invoice id:
<b>{{customers.customer_uid}}</b>
</p>
<p>{{customers.product_warrenty}}</p>
</div>
</div>
</div>
</div>
<div class="customer_product_and_paid_info">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="">
<table class="table table-bordered">
<thead>
<tr>
<th>Product Name</th>
<th colspan="">Price</th>
<th>ID or IME</th>
<th>Warrenty</th>
<th>QN</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<b>{{customers.customer_product_name}}</b>
</td>
<td>
<b>{{customers.customer_price}}</b> TK
<i>{% if customers.customer_discount_taka %} Discount added TK: {{customers.customer_discount_taka}}
TK {% else %} {% endif %}</i>
</td>
<td>{{customers.customer_product_id}}</td>
<td>
{% if customers.customer_product_warrenty %} {{customers.customer_product_warrenty}} Months {% else %} No {% endif %}
</td>
<td>{{customers.customer_product_quantity}}</td>
</tr>
<th>
<hr> First Time Payment</th>
<th>
<hr> {{customers.customer_first_time_payment}} TK
<span style="color:red">{{customers.customer_first_due_info}}</span>
</th>
<td>
<hr> {{customers.customer_sell_date}}
</td>
{% if due_taka_track %}
<thead>
<tr>
<th>SL</th>
<th>Taka</th>
<th>Paid Date</th>
<td>Due Info</td>
</tr>
</thead>
<tbody>
<hr> {% for track in due_taka_track %}
<tr>
<td>{{forloop.counter}}</td>
<td>
<i>{{track.customer_due}}</i> TK</td>
<td>{{track.customer_due_date}}</td>
<td>{{track.customer_due_info}}</td>
</tr>
{% endfor %}
</tbody>
{% else %} {% endif %} {% if sum_cost_taka %}
<tr>
<td>Total Due Complete </td>
<th>{{sum_cost_taka}} TK</th>
</tr>
{% else %} {% endif %}
<tr>
<td>
<b>Total Paid</b>
</td>
<th>
{% if payment_message %}
{{customers.customer_due_taka_info}} TK
<span style="color:red">{{payment_message}}</span>
<br>
<button type="button" class="btn btn-danger">{{remain_msg}} {{remain_taka}} TK</button>
{%else %}
{{customers.customer_due_taka_info}} TK
<button type="button" class="btn btn-success">Payment Completed</button>
{% endif %}
</th>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="customer_notifications">
<div class="container">
<div class="row">
<div class="col-lg-6">
{% if customers.customer_conditions %}
<div class="warning">
<p style="font-size:8px; width:500px;line-height:15px;">
<i>{{customers.customer_product_name}} {{customers.customer_conditions}}</i>
</p>
</div>
{% else %} {% endif %}
</div>
</div>
</div>
</div>
<div class="footer" style="display:block">
<div class="footer_info">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="footer_info">
<p>Print date: {{time_now}}</p>
<p>
<b>বিঃদ্রঃ ডেলিভারির সময় মাল বুঝিয়া নিবেন। পরে কোন আপত্তী গ্রহনযোগ্য নয়</b>
</p>
<p>বিক্রিত মাল ফেরত নেওয়া হয় না</p>
</div>
<div class="copy_right">
{% if site_credit %}
<p>{{site_credit}}</p>
{% else %}
{% endif %}
</div>
</div>
</div>
</div>
</div>
</div>
</body>
Problem
I have a list of 100 golf courses and I'm looking to insert a div, containing an image for an ad after every fifth course. How would I go about doing this?
Update #1
content.html (Revised, newest version)
I've updated my original code snippet because off of leovp's
suggested edited below. I'm having trouble showing only {% if content.featured == "Test" %} and wondering how I should closing my if-else statement.
{% for content in COPY.courses %}
<div class="course course--featured">
<img src="" class="course__image image--region">
<div class="course__inner">
<div class="course__wrapper">
{% if content.state == "MO" %}
<p class="course__state">Missouri</p>
{% elif content.state == "IL" %}
<p class="course__state">Missouri</p>
{% endif %}
</div>
<div class="course__wrapper">
<p class="course__name name--region">{{ content.name }}</p>
</div>
<p class="course__desc">{{ content.description }}</p>
</div>
</div>
{% if loop.index % 5 == 0 %}
<div class="advertising advertising--inline">
<div class="ad ad--rect">
<div class="text-center hidden-xs">
<div id="fixed-leaderboard-region-top"
class="dfp-ad"
data-dfp-custom-pos="fixed-leaderboard-top, htf"
data-dfp-size="[728,90]">
</div>
</div>
<div class="text-center hidden-sm hidden-md hidden-lg">
<div id="fixed-leaderboard-region-top-mobile"
class="dfp-ad"
data-dfp-custom-pos="fixed-leaderboard-top, htf"
data-dfp-size="[320,50]">
</div>
</div>
</div>
</div>
{% endif %}
{% endfor %}
</div>
content.html (Previous, old version for comparision)
I've looked into using batch from this Stack Overflow question that seemed similar, but I'm unsure if this solves my problem?
{% for content in COPY.courses %}
{% if content.featured == "Test" %}
<div class="course__inner">
<div class="course__wrapper">
{% if content.state == "MO"%}
<p class="course__state">Missouri</p>
{% elif content.state == "IL" %}
<p class="course__state">Illinois</p>
{% endif %}
</div>
<div class="course__wrapper">
<p class="course__name name--home">{{ content.name }}</p>
</div>
<p class="course__desc">{{ content.description }}</p>
</div>
{% endif %}
{% endfor %}
While iterating, you can get the current index and check if it's divisible by 5:
{% set count = 0 %}
{% for content in COPY.courses %}
{% if content.featured == "Test" %}
<div class="course course--featured">
<img src="" class="course__image image--home">
[...]
</div>
</div>
{% set count = count + 1 %}
{% if count % 5 == 0 %}
<!-- additional content once every 5 courses -->
{% endif %}
{% endif %}
{% endfor %}
NOTE: This approach no longer works after version 2.10.
For detail see:
How to increment a variable on a for loop in jinja template?