Django model methods(Date filter) - python

Been struggling for weeks now with this issue, starting to feel like I will never solve it.
I have these methods under my model.
def sfget_totals(self):
return self.agent_sale.filter(Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_confirmed(self):
return self.agent_sale.filter(State="Confirmed",Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_debi(self):
return self.agent_sale.filter(AcknowledgeQA=True,State="Confirmed",Debi_status="Accepted",Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_requested(self):
return self.agent_sale.filter(Debi_status="Requested",Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_cancelled(self):
return self.agent_sale.filter(State="Cancelled",Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_pending(self):
return self.agent_sale.filter(State="Pending",Date_created__range=["2022-03-01","2022-04-02"]).count()
in the above example i am putting the dates in manually(it works and returns the correct query)
problem is I still don't know how to make the user plug these dates in through the site.
This is my view.
def Team_stats(request,pk):
sd = request.GET.get("from")
ed = request.GET.get("to")
start_date = datetime.datetime.strptime(sd, "%Y-%m-%d").date()
end_date = datetime.datetime.strptime(ed, "%Y-%m-%d").date()
if start_date == None or end_date == None:
sales_agent = SalesAgent.objects.filter(Team_leader=pk)
return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent})
else:
sales_agent = SalesAgent.objects.filter(Team_leader=pk,agent_sale__Date_created__range=[start_date,end_date]).distinct()
print(type(start_date))
return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent})
This is my template.
I need to render all the agents under the team leader and the particular field of another model. For example State,Date_Created,Debi_status.
<form method="GET" action=".">
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Start date</label>
<input type="date" format='%Y-%m-%d' name="from" class="form-control" id="inputEmail4" placeholder="Start Date">
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">End date</label>
<input type="date" format='%Y-%m-%d' name="to" class="form-control" id="inputEmail4" placeholder="End date">
</div>
</div>
<button type="submit" class="btn btn-primary">Search</button>
</form>
<!-- <p>THERE SHOULD BE A GRAPH IN HERE FOR THE AGENTS STATS</p> -->
<br>
<br>
<div class="container">
<table class="table table-dark table-striped table-bordered">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Agent Name</th>
<th scope="col">Total sales</th>
<th scope="col">Total debis</th>
<th scope="col">Total confirmed</th>
<th scope="col">Total requested</th>
<th scope="col">Total pending</th>
<th scope="col">Total cancelled</th>
</tr>
</thead>
{% for entry in sales_agent %}
<tbody>
<td>{{forloop.counter}}</td>
<td>{{entry.SA_name}}</td>
<td>{{entry.sfget_totals}}</td>
<td>{{ entry.sfget_debi}}</td>
<td>{{ entry.sfget_confirmed}}</td>
<td>{{ entry.sfget_requested}}</td>
<td>{{ entry.sfget_cancelled}}</td>
<td>{{ entry.sfget_pending}}</td>
{%endfor%}
</table>
<div>
<a type="button" class="btn btn-dark btn-m" href="{%url 'Sales:salesdash'%}">Go back</a>
{%endblock%}

I don't know how to do it better. It's not the best answer because you have to iterate through the entire queryset. But I think it works:
1- Change your models methods adding the variables "from" and "to":
#example
def sfget_totals(self, from, to): #
return self.agent_sale.filter(Date_created__range=[from,to]).count()
2- In your views.py, iterate and add the new properties to each item of the queryset:
def Team_stats(request,pk):
sd = request.GET.get("from")
ed = request.GET.get("to")
start_date = datetime.datetime.strptime(sd, "%Y-%m-%d").date()
end_date = datetime.datetime.strptime(ed, "%Y-%m-%d").date()
if start_date == None or end_date == None:
sales_agent = SalesAgent.objects.filter(Team_leader=pk)
return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent})
else:
sales_agent = SalesAgent.objects.filter(Team_leader=pk,agent_sale__Date_created__range=[start_date,end_date])
for s in sales_agent:
s.sfget_totals_prop = s.sfget_totals(start_date,end_date)
s.sfget_confirmed_prop = s.sfget_confirmed(start_date,end_date)
s.sfget_debi_prop = s.sfget_debi(start_date,end_date)
....
....
return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent})
3- In your templates, change the methods name by the new properties:
<td>{{entry.sfget_totals_prop}}</td>
<td>{{ entry.sfget_debi_prop}}</td>
<td>{{ entry.sfget_confirmed_prop}}</td>
<td>{{ entry.sfget_requested_prop}}</td>
<td>{{ entry.sfget_cancelled_prop}}</td>
<td>{{ entry.sfget_pending_prop}}</td>
Probably, you can solve the problem using Django Managers https://docs.djangoproject.com/en/4.0/topics/db/managers/ and you will find a better way.

Related

Django Custom User update with one to one to Customer model

I'm trying to create Update view for Customer model which have Onetoone relation with User(django model. After five hours and trying function base and class views I'm unable to get this working. Where am I making a mistake?
my models.py
class Customer(Model):
user = OneToOneField(User, on_delete=CASCADE)
mobile = CharField(max_length=12,null=True)
dob = DateField(null=True)
def __str__(self):
return self.user.username
my views.py
class ProfileUpdateView(UpdateView):
template_name = 'forms.html'
form_class = AdminUserUpdateForm
model = User
success_url = reverse_lazy('controls')
def get_object(self, queryset=None):
return Customer.objects.get(pk=self.kwargs['pk']).user
# Not working
def customer_list_view(request):
customer = Customer.objects.filter(user__groups__name='customer')
premium = Customer.objects.filter(user__groups__name='premium')
context = {'customer': customer, 'premium': premium}
return render(request, 'customercontrol.html', context)
my forms.py
class AdminUserUpdateForm(UserChangeForm):
class Meta:
model = User
fields = ['username', 'email', 'groups']
mobile = CharField(max_length=30)
dob = DateField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form-control'
#atomic
def save(self, commit=True):
user = super().save(commit)
mobile = self.cleaned_data['mobile']
dob = self.cleaned_data['dob']
customer = Customer.objects.get(user__pk=user.pk)
customer.mobile = mobile
customer.dob = dob
if commit:
customer.save()
return user
my templates, where I get PK for the queries.
{% extends "base.html" %}
{% block content %}
<h1 class="font1">Our premium customers:</h1>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">User ID</th>
<th scope="col"><a class="btn btn-secondary" href="">Username</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Name</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Email</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Phone</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Date of Birth</a></th>
</tr>
</thead>
<tbody>
{% for c in premium %}
<tr>
<td>{{c.id}}</td>
<td>
{{ c.user.username }}</td>
<td>{{c.user.first_name}} {{c.user.last_name}} </td>
<td>{{ c.user.email}}</td>
<td>{{ c.mobile}}</td>
<td>{{ c.dob}}</td>
<td><ul>{% for item in c.user.groups.all %}<li>{{ item}}</li>{% endfor %}</ul></td>
<td><a class="btn btn-danger" href="{% url 'user-delete' c.id %}">Delete</a></td>
<td><a class="btn btn-success" href="{% url 'user-update' c.pk %}">Update</a></td>
</tr>
{% endfor %}
</tbody>
</table>
<h1 class="font1">Our customers:</h1>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">User ID</th>
<th scope="col"><a class="btn btn-secondary" href="">Username</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Name</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Email</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Phone</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Date of Birth</a></th>
</tr>
</thead>
<tbody>
{% for c in customer %}
<tr>
<td>{{c.id}}</td>
<td>
{{ c.user.username }}</td>
<td>{{c.user.first_name}} {{c.user.last_name}} </td>
<td>{{ c.user.email}}</td>
<td>{{ c.mobile}}</td>
<td>{{ c.dob}}</td>
<td><ul>{% for item in c.user.groups.all %}<li>{{ item}}</li>{% endfor %}</ul></td>
<td><a class="btn btn-danger" href="{% url 'user-delete' c.id %}">Delete</a></td>
<td><a class="btn btn-success" href="{% url 'user-update' c.pk %}">Update</a></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
the one with form
{% extends "base.html" %}
{% block content %}
<form method="post">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Submit" class="btn btn-primary">
</form>
{% endblock %}
urls.py
path('<int:pk>/groupupdate', GroupUpdateView.as_view(), name='groupdate'),
path('customercontrol', customer_list_view, name='customercontrol'),
I found solution to my own problem, I had to add function into my view which is passing initial data into form:
def get_initial(self):
initial = super().get_initial()
initial['dob'] = Customer.objects.get(pk=self.kwargs['pk']).dob
initial['mobile'] = Customer.objects.get(pk=self.kwargs['pk']).mobile
return initial

Formatting number in python to bank account format

I have tried looking around finding out how to format a number in python to this specific format. Formatting a number to a currency format was pretty easy to figure out but doing this was not.
<td>{{ "{:,.2f} NOK".format(acc['AccountBalance']) }}</td>
So I simply want to format 12345678901 to 1234.56.78901. I want to use this in my flask template website. Every number is always 11 digits, and it should be formatted as 4 digits period 2 digits period 5 digits period.
EDIT: This is being used in a Flask template, on numbers retrieved from an SQLite table and put into a list. It is the accs['ID'] that is getting this formatting done on it.
accs = db.execute(
'SELECT a.ID, ownerID, AccountBalance, AccountName'
' FROM atbl_bank_accounts a JOIN atbl_system_users u ON a.ownerID = u.ID'
' WHERE a.ownerID = ?',
(g.user['ID'],)
).fetchall()
This again is posted in to a table on the website using flask template as so:
<table class="table table-striped table-hover table-borderless mt-5">
<thead>
<tr>
<th class="col-2" scope="col">Account Number</th>
<th class="col-4" scope="col">Account Name</th>
<th class="col-4" scope="col">Amount left</th>
<th class="col-2" scope="col">Actions</th>
</tr>
</thead>
<tbody>
{% for acc in accs %}
<tr>
<th scope="row">{{ acc['ID'] }}</th>
<td>{{ acc['AccountName'] }}</td>
<!--<td>{{ acc['AccountBalance'] }}</td>-->
<td>{{ "{:,.2f} NOK".format(acc['AccountBalance']) }}</td>
<td>
<button type="button" class="btn btn-light" data-toggle="tooltip" data-placement="top" title="Edit name of account"><i class="fas fa-edit"></i></button>
<button type="button" class="btn btn-light" data-toggle="tooltip" data-placement="top" title="Transfer money from account"><i class="fas fa-file-invoice-dollar"></i></button>
<button type="button" class="btn btn-light" data-toggle="tooltip" data-placement="top" title="Delete account"><i class="fas fa-trash"></i></button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
So I either need a solution that works straight in the HTML or in the python script. Apologies for not being clear enough.
I did search a fair bit around, but if I skipped an article about this I'm sorry.
Thanks for the answers in advance.
Turn the integer to a str and use slices along with join.
In [22]: p = 12345678901
In [23]: q = str(p)
In [24]: '.'.join((q[:4],q[4:-5],q[-5:]))
Out[24]: '1234.56.78901'
Or you could use slice objects which is basically the same thing but you get to name them.
In [33]: first, middle, last = slice(0,4),slice(4,-5),slice(-5,None)
In [34]: '.'.join((q[first],q[middle],q[last]))
Out[34]: '1234.56.78901'
Thanks to NoNickAvailable and wwii for the tips.
Since I was using this is with a flask template and for loop, I couldn't use wwii's answer directly. With help from this stackoverflow article, I managed to make a working version.
I retrive the data from the database as follows:
accs = db.execute(
'SELECT a.ID, ownerID, AccountBalance, AccountName'
' FROM atbl_bank_accounts a JOIN atbl_system_users u ON a.ownerID = u.ID'
' WHERE a.ownerID = ?',
(g.user['ID'],)
).fetchall()
Then I had to use dict:
IDrows = [dict(row) for row in accs]
Then to format the numbers with my very specific format I used what wwii and NoNickAvailable answered:
for i in IDrows:
i['ID'] = '.'.join((str(i['ID'])[:4],str(i['ID'])[4:-5],str(i['ID'])[-5:]))
The numbers were than all individually formatted and easily inserted into my table:
<table class="table table-striped table-hover table-borderless mt-5">
<thead>
<tr>
<th class="col-2" scope="col">Account Number</th>
<th class="col-4" scope="col">Account Name</th>
<th class="col-4" scope="col">Amount left</th>
<th class="col-2" scope="col">Actions</th>
</tr>
</thead>
<tbody>
{% for acc in IDrows %}
<tr>
<th scope="row">{{ acc['ID'] }}</th>
<td>{{ acc['AccountName'] }}</td>
<!--<td>{{ acc['AccountBalance'] }}</td>-->
<td>{{ "{:,.2f} NOK".format(acc['AccountBalance']) }}</td>
<td>
<button type="button" class="btn btn-light" data-toggle="tooltip" data-placement="top" title="Edit name of account"><i class="fas fa-edit"></i></button>
<button type="button" class="btn btn-light" data-toggle="tooltip" data-placement="top" title="Transfer money from account"><i class="fas fa-file-invoice-dollar"></i></button>
<button type="button" class="btn btn-light" data-toggle="tooltip" data-placement="top" title="Delete account"><i class="fas fa-trash"></i></button>
</td>
</tr>
{% endfor %}
</tbody>
</table>

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 get data from a form to jinja2

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.

Categories

Resources