How to get data from a form to jinja2 - python

I am trying to get a value inputted through a form and then back into my jinja template. Which I know doesn't make sense so I guess I am asking how do I go about doing what I want?. Here is what I have:
Python
#app.route('/test', methods=['GET', 'POST'] )
def test():
posts = db.posts
facultyId = request.form.get("facultyId","");
print "facultyId: ",facultyId
return render_template('form.html',posts=posts,Id=facultyId)
form.html
<form method='post'>
<table width="80%" border="5" align="center" bgcolor="white">
<tbody>
<tr>
<th colspan= "4">
Faculty Identification Number:
<input type="text" id="facultyId" name="facultyId" value=""/>
</th>
</tr>
<tr>
<th colspan= "4">
Number Of Evaluations:
{% if posts.find({"Applicants.appId" : Id},{'Applicants.Evaluators':{'$exists': True }}).count() == 0 %}
{{posts.find({"Applicants.appId" : Id},{'Applicants.Evaluators':{'$exists': True }}).count() }}
{% else %}
{% for post in posts.find({"Applicants.appId" : Id}, { "Applicants.$.Evaluators" : 1 }) %}
{{post["Applicants"][0]["Evaluators"]|length}}
{% endfor %}
{% endif %}
</th>
</tr>
<th colspan= "4"><button type="submit" >Submit</button></th>
</tbody>
</table>
</form>
I want to be able to submit a facultyId though a form and have it go into my jinja and run my mongodb find query. It works if I hard code the value in so if I did Id=100 in my python it works but if I do it though the forums it doesn't and the facultyId value is getting inputted because it does prints out.

Try to set action controller as follows
<form method='post' action='/test'>

I think the problem is that you do not parse facultyId as an integer. It works if you hardcode 100, because it is an integer, but what you assign out of request.form is a string "100".
After
facultyId = request.form.get("facultyId","")
add
facultyId = int(facultyId) if facultyId else None

Try to put it in braces. Like this:
<form method='post'>
<table width="80%" border="5" align="center" bgcolor="white">
<tbody>
<tr>
<th colspan= "4">
Faculty Identification Number:
<input type="text" id="facultyId" name="facultyId" value=""/>
</th>
</tr>
<tr>
<th colspan= "4">
Number Of Evaluations:
{% if posts.find({"Applicants.appId" : {{Id}}},{'Applicants.Evaluators':{'$exists': True }}).count() == 0 %}
{{posts.find({"Applicants.appId" : {{Id}}},{'Applicants.Evaluators':{'$exists': True }}).count() }}
{% else %}
{% for post in posts.find({"Applicants.appId" : {{Id}}}, { "Applicants.$.Evaluators" : 1 }) %}
{{post["Applicants"][0]["Evaluators"]|length}}
{% endfor %}
{% endif %}
</th>
</tr>
<th colspan= "4"><button type="submit" >Submit</button></th>
</tbody>
</table>
</form>

I would also suggest to put your posts.find logic into your route function, then pass it's results to your form in the posts variable.

Related

Not able to send checkbox data from all pagination in datatable from template to view in django

I have a datatable in my django template in which there is a checkbox next to every row to send the row data to a view function to make some mass updations in django model. But problem is if the multiple rows are on the same page in pagination then i can send the data accurately BUT if i select row 2 from page 1 and row 5 from page 3 only the row value from page 3 will be sent to the view function.!
TEMPLATE.HTML
{% block jquery %}
<script type="text/javascript" class="init">
$(document).ready( function ($) {
var $submit = $("#updiv").hide(),
$cbs = $('input[name="updelegate"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
$('#myTable').DataTable({
dom: 'lBfrtip',
"pageLength": 1,
"language": {
"emptyTable": "No Delegates Available",
"sSearch": "Search Delegates: ",
"info": " Showing _START_-_END_ out of Total _TOTAL_ Delegates",
}
});
});
</script>
{% endblock %}
<form id="myForm" action="{% url 'mass-delegates' %}" method="POST">
{% csrf_token %}
<table id="myTable" class="table table-striped table-bordered" style="width:100%">
<thead class="thead-dark">
<tr>
<th></th>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Phone</th>
<th scope="col">Company</th>
<th scope="col">Designation</th>
<th scope="col">Address</th>
<th scope="col">City</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{% for del in delegates %}
<tr>
<td>
<label class="container">
<input type="checkbox" id="updelegate" name="updelegate"
value="{{ del.id }}">
<span class="checkmark"></span>
</label>
</td>
<td>{{ del.id }}</td>
<td>{{ del.first_name }} {{ del.last_name }}</td>
<td>{{ del.email }}</td>
<td>{{ del.phone }}</td>
<td>{{ del.company }}</td>
<td>{{ del.designation }}</td>
<td>{{ del.address }}</td>
<td>{{ del.city }} ({{ del.pincode }})</td>
<td>
View
</td>
<td>
Edit
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div id="updiv">
<select name="eventid">
{% for ev in events %}
<option value="{{ ev.id }}">{{ ev.name }}</option>
{% endfor %}
</select>
<input type="submit" onclick="return confirm('Confirm Adding to Event?');" class="upbtn"
name="update" value="Add to Event"/>
</div>
</form>
VIEW.PY
def mass_delegates(request):
if request.method == 'POST':
toupdate = request.POST.getlist('updelegate')
eventid = request.POST.get('eventid')
array_length = len(toupdate)
for i in range(array_length):
if not EventDelegate.objects.filter(event_id=eventid, delegate_id=toupdate[i]).exists():
EventDelegate.objects.create(event_id=eventid, delegate_id=toupdate[i])
return event_det(request, eventid)
Instead of using the checkboxes, you can directly use the select attribute in the Datatables api. Check Select Rows in Datatables
Moreover, Since you want to select multiple rows at once, you might consider checking Multi Select rows in Datatables out
You can add the id in the 0th column, then
dataTable = $(.selector).Datatable()
dataTable.columns([0]).visible(false);
You can hide the column like that and then when you send your request, you still have your id

How to select/unselect/delete multiple django items in a table with the same checkbox?

I have this table of items with their details, and I have implemented a method to 'select' a few items using a submit button, which submits all checked checkboxes on each item.
This is the code for the checkbox:
<input name='quiz-pids' id='checkbox-{{ quiz.id }}' type="checkbox" value="{{ quiz.id }}" required>
As you can see, I have passed the quiz.id in the checkbox value. This is my submit button I am using:
<input type="submit" class="btn btn-primary select-btn myitems-select-btn"
value='Finalize Items'
required>
Here, I have not mentioned what this button will do except than submit. This is the function which processes the data input by submit button.
class UploadedItems(ListView):
model = ItemBatch
ordering = ('uploaded',)
context_object_name = 'plan'
template_name = 'classroom/teachers/item_list.html'
def post (self, request, *args, **kwargs):
# get the selected quizs
quizs = request.POST.getlist('quiz-pids')
# retrieves thoses quizes from the database:
print("pids returned are ", quizs)
# items = ItemBatch.objects.filter(pid__in=quizs)
for i in quizs:
print("before", i)
i = get_object_or_404(ItemBatch, id=i)
i.rtd = 'True'
i.save()
print("after", i.truck_type) # print("items are",items)
return redirect('teachers:upload_batch')
As you can see, my function 'post' accepts only quiz-pids because of this line request.POST.getlist('quiz-pids'). Now my question is, I also want to delete and unselect my items. But, because my function can only accept quiz-pids, I cannot just create another button for that.
What I tried
I tried adding more functions:
def post (self, request, *args, **kwargs):
# get the selected quizs
quizs = request.POST.getlist('quiz-pids')
deleted_items = request.POST.getlist('delete-pids')
unselect_items = request.POST.getlist('unselect-pids')
# retrieves thoses quizes from the database:
print("pids returned are ", quizs)
# items = ItemBatch.objects.filter(pid__in=quizs)
for i in quizs:
print("before", i)
i = get_object_or_404(ItemBatch, id=i)
i.rtd = 'True'
i.save()
print("after", i.truck_type) # print("items are",items)
for j in unselect_items:
j = get_object_or_404(ItemBatch, id=i)
j.rtd = 'False'
j.save()
for k in deleted_items:
k = get_object_or_404(ItemBatch, id=i)
k.delete()
k.save()
But, because every checkbox I have in front of my items, has the name name='quiz-pids', I am not able to generate a deleted_items list or unselect_items list. I cannot possibly give three different checkboxes to every item. What should I do?
Here is my complete html and views function:
#method_decorator([login_required, teacher_required], name='dispatch')
class UploadedItems(ListView):
model = ItemBatch
ordering = ('uploaded',)
context_object_name = 'plan'
template_name = 'classroom/teachers/item_list.html'
def get_queryset (self):
return ItemBatch.objects.filter(uploaded_by=self.request.user)
def get_context_data (self, **kwargs):
context = super().get_context_data(**kwargs)
latest = ItemBatch.objects.filter(uploaded_by=self.request.user).order_by('-time').annotate(
truncated_time=Trunc('time', 'minute', output_field=DateTimeField()))
context['last'] = ItemBatch.objects.filter(uploaded_by=self.request.user).annotate(
truncated_time=Trunc('time', 'minute', output_field=DateTimeField())).filter(
truncated_time=Subquery(latest.values('truncated_time')[:1])).order_by('-rtd')
return context
def post (self, request, *args, **kwargs):
# get the selected quizs
quizs = request.POST.getlist('quiz-pids')
deleted_items = request.POST.getlist('delete-pids')
unselect_items = request.POST.getlist('unselect-pids')
# retrieves thoses quizes from the database:
print("pids returned are ", quizs)
# items = ItemBatch.objects.filter(pid__in=quizs)
for i in quizs:
print("before", i)
i = get_object_or_404(ItemBatch, id=i)
i.rtd = 'True'
i.save()
print("after", i.truck_type) # print("items are",items)
for j in unselect_items:
j = get_object_or_404(ItemBatch, id=i)
j.rtd = 'False'
j.save()
for k in deleted_items:
k = get_object_or_404(ItemBatch, id=i)
k.delete()
k.save()
print("pids converted are ", quizs)
return redirect('teachers:upload_batch')
HTML template:
{% extends 'base2.html' %}
{% load static %}
{% load tz humanize %}
{% timezone "Asia/Kolkata" %}
{% block content %}
<h2>Orders</h2>
{% include 'classroom/teachers/inventory_header.html' with active='myitems' %}
<h2 class="align-left"> Your Last Uploaded Items</h2>
{#Post New Bid#}
<div class="card last-items">
<form method="post" novalidate>
{% csrf_token %}
<table class="table table-striped mb-0" id="items">
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>SKU ID</th>
<th>Quantity</th>
<th>Dimensions</th>
<th>Volume/Weight</th>
<th>Origin</th>
<th>Destination</th>
<th>Type</th>
<th>Uploaded</th>
<th>Dispatch Status</th>
</tr>
</thead>
<tbody>
<input type="checkbox" id="selectall" class="css-checkbox btn btn-primary" name="selectall"/>Select
All
{% for quiz in last %}
<input type="submit" class="btn btn-primary select-btn myitems-select-btn"
value='Finalize Items'
required>
<input type="submit" class="btn btn-primary select-btn myitems-select-btn"
value='Unselect Items'
required>
<input type="submit" class="btn btn-primary select-btn myitems-select-btn"
value='Delete Items'
required>
<a href="{% url 'teachers:pack_it' %}"
class="btn btn-primary mb-3 myitems-select-btn {% if quiz.rtd == 0 %} disabled {% endif %}"
role="button">Plan Vehicles</a>
<tr class="{% if quiz.rtd == True %} active{% endif %} {% if quiz.is_dispatched == True %} dispatched{% endif %}">
<td class="align-middle"><input name='quiz-pids' id='checkbox-{{ quiz.id }}'
type="checkbox" value="{{ quiz.id }}" required
{% if quiz.is_dispatched == 1 %} disabled{% endif %} ></td>
<td class="align-middle">{{ quiz.name }}</td>
<td class="align-middle">{{ quiz.pid }}</td>
<td class="align-middle">{{ quiz.quantity }}</td>
<td class="align-middle">{{ quiz.length }}x{{ quiz.width }}x{{ quiz.height }}</td>
<td class="align-middle">{{ quiz.volume|truncatechars:8 }}/{{ quiz.weight }}</td>
<td class="align-middle">{{ quiz.origin }}</td>
<td class="align-middle">{{ quiz.destination }}</td>
<td class="align-middle">{{ quiz.truck_type }}</td>
<td class="align-middle">{{ quiz.time|naturaltime }}</td>
<td class="align-middle">{{ quiz.is_dispatched|yesno:"Dispatched,Ready to Dispatch" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
</div>
<br>
<br>
<h2 class="align-left">All your Uploaded Items</h2>
<br>
<div class="card">
<table class="table table-striped mb-0" id="items">
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>SKU ID</th>
<th>Quantity</th>
<th>Dimensions</th>
<th>Volume/Weight</th>
<th>Origin</th>
<th>Destination</th>
<th>Type</th>
<th>Uploaded</th>
<th>Dispatch Status</th>
</tr>
</thead>
<tbody>
<form method="post" novalidate>
{% csrf_token %}
{% for quiz in plan %}
<input type="submit" class="btn btn-primary select-btn myitems-select-btn"
value='Finalize Items'
required>
<a href="{% url 'teachers:pack_it' %}"
class="btn btn-primary mb-3 myitems-select-btn {% if quiz.rtd == 0 %} disabled {% endif %}"
role="button">Plan Vehicles</a>
<tr class="{% if quiz.rtd == True %} active{% endif %} {% if quiz.is_dispatched == True %} dispatched{% endif %}">
<td class="align-middle"><input name='quiz-pids' id='checkbox-{{ quiz.id }}'
type="checkbox" value="{{ quiz.id }}" required
{% if quiz.is_dispatched == 1 %} disabled{% endif %} ></td>
<td class="align-middle">{{ quiz.name }}</td>
<td class="align-middle">{{ quiz.pid }}</td>
<td class="align-middle">{{ quiz.quantity }}</td>
<td class="align-middle">{{ quiz.length }}x{{ quiz.width }}x{{ quiz.height }}</td>
<td class="align-middle">{{ quiz.volume }}/{{ quiz.weight }}</td>
<td class="align-middle">{{ quiz.origin }}</td>
<td class="align-middle">{{ quiz.destination }}</td>
<td class="align-middle">{{ quiz.truck_type }}</td>
<td class="align-middle">{{ quiz.time|naturaltime }}</td>
<td class="align-middle">{{ quiz.is_dispatched|yesno:"Dispatched,Ready to Dispatch" }}</td>
</tr>
<tr>
{% empty %}
<td class="bg-light text-center font-italic" colspan="9">You haven't uploaded any items yet.
</td>
</tr>
{% endfor %}
</form>
</tbody>
</table>
</div>
<link rel="stylesheet" href="http://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
{# <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>#}
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#items').DataTable({
"pagingType": "full_numbers",
"bDestroy": true
});
});
</script>
<script>
$('#selectall').click(function () {
var checkedStatus = this.checked;
$('input:checkbox').each(function () {
$(this).prop('checked', checkedStatus);
});
});
</script>
{% endblock %}
{% endtimezone %}
Anybody has any doubts? or need more information?

How to print table using Jinja2 (without page refresh)

I use Pandas to get and transform some data from database and now I'd like to print the score dynamic, that is without page refresh. I've already tried: {{ mydata|safe}} and I get the whole information but everything is together not in table.
I use Pandas to create HTML table from dataframe mydata.to_html()) and I get something like that:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Part_number</th>
<th>Type_name</th>
<th>Short_desc</th>
<th>Price_1</th>
<th>Price_2</th>
<th>VAT</th>
<th>DB_source</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>565_MLNN7_101</td>
<td>AIR_FILTER</td>
<td>AIR_FILTER_GREEN</td>
<td>1.20</td>
<td>6.30</td>
<td>23%</td>
<td>Murexin</td>
</tr>
<tr>
<th>1</th>
<td>217_NE307_115</td>
<td>CABLE</td>
<td>CABLE_POWER_AC</td>
<td>0.84</td>
<td>3.20</td>
<td>23%</td>
<td>DB_1</td>
</tr>
</tr>
</tbody>
</table>
Do You know how print the table using Jinja2 ?
The jinja template that you need is something like this:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Part_number</th>
<th>Type_name</th>
<th>Short_desc</th>
<th>Price_1</th>
<th>Price_2</th>
<th>VAT</th>
<th>DB_source</th>
</tr>
</thead>
<tbody>
{% for row in mydata %}
<tr>
<th>{{loop.index0}}</th>
<td>{{row['Part_number']}}</td>
<td>{{row['Type_name']}}</td>
<td>{{row['Short_desc']}}</td>
<td>{{row['Price_1']}}</td>
<td>{{row['Price_2']}}</td>
<td>{{row['VAT']}}</td>
<td>{{row['DB_source']}}</td>
</tr>
{% endfor %}
</tbody>
</table>
Check jinja2 documentation for more details
Sure
Here is my code for html template:
{% extends "header.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block content %}
<div class="container">
<form class="form-signin" method="POST" action="/search">
<div class="panel panel-default">
<div class="panel-heading">Service Part Inquiry</div>
<div class="panel-body">
{{ form.hidden_tag() }}
{{wtf.form_field(form.FGPN_Search)}}
{{wtf.form_field(form.AssyTypeName_Search)}}
{{wtf.form_field(form.Source_Search)}}
<button type="submit" class="btn btn-primary btn-xsy">Search</button>
</div>
</div>
</form>
</div> <!-- /container -->
{{data|safe}}
{% endblock %}
Code for function below. Actually I check condition only for "Source_Search": "Murexin", that why I deleted some codes (will be easier to understand for You :) I respect Your time):
#app.route('/search',methods=['GET', 'POST'])
def search():
form = SearchForm()
if request.method == 'POST':
FGPN_Search = form.FGPN_Search.data
AssyTypeName_Search = form.AssyTypeName_Search.data
Source_Search = form.Source_Search.data
(...)
elif Source_Search == 'Murexin':
if len(FGPN_Search)>1:
tablePLM=read_sql_query(select1 + "\'" + FGPN_Search + "\'" + select2 + "\'" + AssyTypeName_Search + "\'",CurDB_2)
tableSIC = read_sql_query(selectSIC + "\'" + FGPN_Search + "\'",CurDB_1)
mydata = pd.merge(tablePLM, tableSIC, on='PM_PARTNUMBER',how='outer')
mydata.to_html()
return render_template('search.html', form=form,data=mydata)
elif Source_Search == 'test':
return "<h1>test</h1>"
else:
flash("Please write anything.")
return render_template('search.html',form=form)
return render_template('search.html', form=form)

Django web page- how to manipulate what information is displayed in a table

I have a Django project, and one of my views renders a page that displays a table with information about objects in the database. The objects displayed differ based on the criteria determined in the view.
The if statement used in the view to determine which page to render is:
if request.GET.get('stage') == 'pd':
print "request.GET.get('stage') == 'pd' "
print "render_to_string() called with parameter: costing/report2_ccis.html"
context['html'] = render_to_string('costing/report2_ccis.html', context)
context['active_tab'] = '4'
if(project.deposit_received == True):
print "costing/reports_post_deposit.html is the page being rendered (project.deposit_received = true)... "
context['post_deposit'] = True
print "context['post_deposit']: ", context['post_deposit']
return render(request, 'costing/reports_post_deposit.html', context)
elif(project.deposit_received == False):
print "costing/reports_pre_deposit.html is the page being rendered (project.deposit_received = False)..."
context['post_deposit'] = False
print "context['post_deposit']: ", context['post_deposit']
return render(request, 'costing/reports_pre_deposit.html', context)
else:
print "request.GET.get('stage') != 'pd' "
print "render_to_string() called with parameter: costing/report_ccis.html"
context['html'] = render_to_string('costing/report_ccis.html', context)
context['active_tab'] = '5'
if(project.deposit_received == True):
print "costing/reports_post_deposit.html is the page being rendered (project.deposit_received = true)..."
context['post_deposit'] = True
print "context['post_deposit']: ", context['post_deposit']
return render(request, 'costing/reports_post_deposit.html', context)
elif(project.deposit_received == False):
print "costing/reports_pre_deposit.html is the page being rendered (project.deposit_received = false)..."
context['post_deposit'] = False
print "context['post_deposit']: ", context['post_deposit']
return render(request, 'costing/reports_pre_deposit.html', context)
Both of the templates returned in the view extend another template called reports_tabbed.html, and the report_ccis.html & report2_ccis.html templates that are passed to the render_to_string view both extends another template called pdf2_base.html.
The table that's displaying the information on the webpage (whichever one is passed to render_to_string- report_ccis.html or report2_ccis.html) is defined in pdf2_base.html with:
<table class="pdf-report left">
{% for payment_details in payments_details %}
{% if forloop.first %}
<thead>
<tr>
{% for detail in payment_details %}
<th>{{ detail.0 }}</th>
{% endfor %}
<th></th>
</tr>
</thead>
{% endif %}
<tbody>
{% if 0 %}
<tr class="end-table-section"></tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
{% endif %}
<tr {% if forloop.last %}class="end-table-section last-row"{% endif %}>
{% for detail in payment_details %}
<td {% if detail.0 == 'Gross payment (£)' %}class="payment-{{detail.2}}"{% endif %}>
{% if detail.1 and detail.0 != 'Date paid' and detail.0 != 'Date' %}
{% if detail.0 == 'VAT (£)' or detail.0 == 'Scheduled payment (£)' or detail.0 == 'Gross payment (£)' %}
{{ detail.1|money }}
{% else %}
{{ detail.1 }}
{% endif %}
{% elif detail.1 %}
{{ detail.1|date:'d-M' }}
{% endif %}
</td>
{% endfor %}
<td></td>
</tr>
{% if 0 %}
<tr class="end-table-section"></tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
{% endif %}
{% endfor %}
<tr class="end-table-section">
<td>Gross payment now due:</td>
<td>{{gross_payment_due|money:'£'}}</td>
<td>Current contract sum</td>
<td>Exc VAT {{ latest_total_exc|money:'£' }}</td>
<td></td>
<td>Bank</td>
<td>Handelsbanken</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Total payments made</td>
<td>Exc VAT {{total_paid_exc|money:'£'}}</td>
<td></td>
<td> acc</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td>Outstanding contract sum</td>
<td>Exc VAT {{outstanding_exc|money:'£'}}</td>
<td>Inc VAT {{outstanding_inc|money:'£'}}</td>
<td>Sort Code</td>
<td></td>
</tr>
<tr class="last-row">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td colspan="2">Please ensure address is put as reference</td>
</tr>
</tbody>
</table>
What I want to do, is change this table in the template when it is displayed by the if(project.deposit_received == False) conditions in the view, so that one of the columns in the table ('Latest Sum') is not displayed in the table... But given that the table is generated & populated using Django for loops, as it changes dynamically based on the information retrieved from the database, I'm not sure how to do this...
Is there a way I can explicitly tell the code, either in the Python or the Django/ HTML not to display a certain column of the table when a particular condition is met?
First of all you can pass to the template some variable through the context and check if it was pre or post deposit.
if(project.deposit_received == True):
context['post_deposit'] = True
return render(request, 'costing/reports_post_deposit.html', context)
elif(project.deposit_received == False):
context['post_deposit'] = False
return render(request, 'costing/reports_pre_deposit.html', context)
So now yoou need to check this value in template:
{% if post_deposit %}
do_something
{% else %}
do_something_else
{% endif %}
And the last one you can check current iteration of cycle in template using forloop.counter. For example if you need to remove 3rd column in post_deposit table you can check if the loop counter equal to 3 and skip iteration:
{% for detail in payment_details %}
{% if not post_deposit or forloop.counter != 3 %}
<th>{{ detail.0 }}</th>
{% endif %}
{% endfor %}

Send table data from template to view.py in django

I am passing a list i.e data_code from view.py to a html file and from there i am printing the data of the table using for loop through the list. There is a editable column in the table <input> and i want to get those data after filled by user on my view.py. so anybody any idea how to do that??
I want to get all {{x.2}} in view.py. It is printing some default value but i want it again after it is being by user.
Here is the code:
<table class="table table-bordered datatable">
<thead class="table-head">
<tr>
<th>No</th>
<th>Code Point</th>
<th>Reference</th>
<th>Character</th>
<th>Text</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{% for x in data_code %}
<tr class="table-row">
<td>{{ forloop.counter }}</td>
<td><label>{{ x.0 }}</label></td>
<td><input id="codepoint_input" type="text" value={{x.2}} size=3 title="Text"></td>
<td><label> {{x.3}}</label></td>
<td>{{x.4}}</td>
</tr>
{% endfor %}
</tbody>
</table>
Edit:
Use dictionary type so that you can give each input box a unique name through the key, and use the corresponding value in value parm.
In view, you can use a for loop to go through the whole dictionary, and use the key to get the values from the template.
In your Template:
<form name = "yourForm" method="GET" action="/" class = "main">
{% for key, value in json.data_code%}
<td>
<input name = "{{ key }}" id="codepoint_input" type="text" value={{ value }} size=3 title="Text">
<input type="submit" id = "amountbtn" style="visibility:hidden;" >
</td>
{% endfor %}
</form>
In your views:
key1 = request.GET.get('key1')
....
The first task is get those entered values using jquery simply...
$(#codepoint_input).keypress(function(e) {
if(e.which == 13) {
// your custom code here.
var tablestring = $("#tableForm").serialize();
$.post( "/backend", tablestring );
}
});
Finally you can get the values in your view function...
def backend(request):
print(request.POST)

Categories

Resources