Trying to query based on choice field django - django

I've been stuck on this all day. I've got a model, Load, within that model it has a choice field with different "statuses". I am trying to implement some tabbed views in my template. So basically each tab will be responsible for displaying a certain status. I believe that I should be using a queryset within my view get_context_data but I'm just not really understanding how to accomplish this. I've tried a ton of different ways in the view, so i'll just paste the latest attempt.
These query's will be static once they are done so my best thought was to use a model managers for each query, but I couldn't get multiple model managers to work on one model. Here's an example of one. Any help would be appreciated. Thank you
class BookedManager(models.Manager):
def get_queryset(self):
return super(BookedManager, self).get_queryset().filter(load_status='Booked')
Models.py
class Load(models.Model):
load_number = models.IntegerField()
agent = models.ForeignKey(User,
limit_choices_to={'groups__name': 'Agent'},related_name='Agent', on_delete=models.CASCADE, null=True)
customer = models.ForeignKey(User,
limit_choices_to={'groups__name': 'Customer'},related_name='Customer', on_delete=models.CASCADE)
carrier = models.ForeignKey(Carrier, on_delete=models.CASCADE, blank=True, null=True)
pickup_date = models.DateField()
delivery_date = models.DateField()
shipper = models.ForeignKey(Location, related_name='shipper', on_delete=models.CASCADE, blank=True)
consignee = models.ForeignKey(Location, related_name='consignee', on_delete=models.CASCADE, blank=True)
po_number = models.CharField(max_length=255)
pu_number = models.CharField(max_length=255)
pieces = models.IntegerField()
description = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
PREBOOK = 'Waiting for Carrier'
BOOKED = 'Booked'
CONFIRMED = 'Confirmed Rate'
PICKED = 'Picked'
DELIVERED = 'Delivered'
INVOICED = 'Invoiced'
PAID = 'Paid'
LOAD_STATUS_CHOICES = (
(PREBOOK, 'Waiting for Carrier'),
(BOOKED, 'Booked'),
(CONFIRMED, 'Signed Rate Confirmation'),
(PICKED, 'Picked Up'),
(DELIVERED, 'Delivered'),
(INVOICED, 'Invoiced'),
(PAID, 'Paid'),
)
load_status = models.CharField(max_length=30, choices=LOAD_STATUS_CHOICES, default=PREBOOK)
def save(self, *args, **kwargs):
LoadUpdateHistory.objects.create(your_model=self, updated=timezone.now())
def get_absolute_url(self):
return reverse('loads:detail',kwargs={'pk':self.pk})
def __str__(self):
return str(self.load_number)
views.py
class LoadListView(ListView):
model = Load
context_object_name = 'loads'
def get_context_data(self, **kwargs):
context = super(LoadListView, self).get_context_data(**kwargs)
context['booked'] = Load.objects.filter(load_status__contains='booked')
return context
Template
{% for load in loads %}
<tr>
<td>{{load.load_number}}</td>
<td>{{load.agent}}</td>
<td>{{user.customer.company_name}}</td>
<td>{{load.carrier}}</td>
<td>{{load.pickup_date}}</td>
<td>{{load.delivery_date}}</td>
<td>{{load.shipper}}</td>
<td>{{load.consignee}}</td>
<td>{{load.po_number}}</td>
<td>{{load.pu_number}}</td>
<td>{{load.date_created}}</td>
<td>
<a href="#">
<button class="btn btn-warning" type="button">
<span class="glyphicon glyphicon-pencil"></span> </button>
</a>
<a href="{% url 'loads:delete' pk=load.pk%}">
<button class="btn btn-danger" type="button">
<span class="glyphicon glyphicon-remove"></span> </button>
</a>
</td>
</tr>
{% endfor %}
Update 1/21/17
Views.py
class LoadListView(ListView):
model = Load
context_object_name = 'loads'
def get_context_data(self, **kwargs):
context = super(LoadListView, self).get_context_data(**kwargs)
"""
This was probably my biggest mistake, I kept trying to query from
Load.load_status, load_status doesn't have a choice, it holds a variable
which then holds a status.
which i'm assuming is why i can't query off of the object load_status.
This new Loop says for the first choice in Load.LOAD_STATUS_CHOICES.
I'm not really understanding why we are selecting the first choice here.
"""
statuses = (choice[0] for choice in Load.LOAD_STATUS_CHOICES)
"""
Then we pass in loads_by_status into the template it filters the load_status
object and gets the status in statuses.
"""
context['loads_by_status'] = {
status: Load.objects.filter(load_status=status) for status in statuses
}
return context
My result in adding this code is that the template is not returning anything so I must be calling the data wrong in the template.
Template
<div>
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist" id='myTab'>
<li role="presentation" class="active">All Loads</li>
<li role="presentation">Waiting For Carrier</li>
<li role="presentation">Booked</li>
<li role="presentation">Confirmed</li>
<li role="presentation">Picked</li>
<li role="presentation">Delivered</li>
<li role="presentation">Invoiced</li>
<li role="presentation">Paid</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane fade in active" id="allLoads">
<h1>All Loads</h1>
<table id="example" class="table table-striped table-bordered" cellspacing="0"
width="100%">
<thead>
<tr>
<th>Load Number</th>
<th>Load Status</th>
<th>Agent</th>
<th>Customer</th>
<th>Carrier</th>
<th>Pickup Date</th>
<th>Delivery Date</th>
<th>Shipper</th>
<th>Consignee</th>
<th>PO Number</th>
<th>PU Number</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Load Number</th>
<th>Load Status</th>
<th>Agent</th>
<th>Customer</th>
<th>Carrier</th>
<th>Pickup Date</th>
<th>Delivery Date</th>
<th>Shipper</th>
<th>Consignee</th>
<th>PO Number</th>
<th>PU Number</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
{% for load in loads %}
<tr>
<td>{{load.load_number}}</td>
<td>{{load.load_status}}</td>
<td>{{load.agent}}</td>
<td>{{user.customer.company_name}}</td>
<td>{{load.carrier}}</td>
<td>{{load.pickup_date}}</td>
<td>{{load.delivery_date}}</td>
<td>{{load.shipper}}</td>
<td>{{load.consignee}}</td>
<td>{{load.po_number}}</td>
<td>{{load.pu_number}}</td>
<td>{{load.date_created}}</td>
<td>
<a href="#">
<button class="btn btn-warning" type="button">
<span class="glyphicon glyphicon-pencil"></span> </button>
</a>
<a href="#">
<button class="btn btn-danger" type="button">
<span class="glyphicon glyphicon-remove"></span> </button>
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div role="tabpanel" class="tab-pane fade" id="waitingForCarrier">
<h1>Waiting For Carrier</h1>
<table id="example" class="table table-striped table-bordered" cellspacing="0"
width="100%">
<thead>
<tr>
<th>Load Number</th>
<th>Load Status</th>
<th>Agent</th>
<th>Customer</th>
<th>Carrier</th>
<th>Pickup Date</th>
<th>Delivery Date</th>
<th>Shipper</th>
<th>Consignee</th>
<th>PO Number</th>
<th>PU Number</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Load Number</th>
<th>Load Status</th>
<th>Agent</th>
<th>Customer</th>
<th>Carrier</th>
<th>Pickup Date</th>
<th>Delivery Date</th>
<th>Shipper</th>
<th>Consignee</th>
<th>PO Number</th>
<th>PU Number</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
{% for status, load in loads_by_status.items %}
<tr>
<td>{{load.load_number}}</td>
<td>{{load.load_status}}</td>
<td>{{load.agent}}</td>
<td>{{user.customer.company_name}}</td>
<td>{{load.carrier}}</td>
<td>{{load.pickup_date}}</td>
<td>{{load.delivery_date}}</td>
<td>{{load.shipper}}</td>
<td>{{load.consignee}}</td>
<td>{{load.po_number}}</td>
<td>{{load.pu_number}}</td>
<td>{{load.date_created}}</td>
<td>
<a href="#">
<button class="btn btn-warning" type="button">
<span class="glyphicon glyphicon-pencil"></span> </button>
</a>
<a href="#">
<button class="btn btn-danger" type="button">
<span class="glyphicon glyphicon-remove"></span> </button>
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div role="tabpanel" class="tab-pane fade" id="booked">
<h1>Booked</h1>
<table id="example" class="table table-striped table-bordered" cellspacing="0"
width="100%">
<thead>
<tr>
<th>Load Number</th>
<th>Load Status</th>
<th>Agent</th>
<th>Customer</th>
<th>Carrier</th>
<th>Pickup Date</th>
<th>Delivery Date</th>
<th>Shipper</th>
<th>Consignee</th>
<th>PO Number</th>
<th>PU Number</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Load Number</th>
<th>Load Status</th>
<th>Agent</th>
<th>Customer</th>
<th>Carrier</th>
<th>Pickup Date</th>
<th>Delivery Date</th>
<th>Shipper</th>
<th>Consignee</th>
<th>PO Number</th>
<th>PU Number</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
{% for status, load in loads_by_status.items %}
<tr>
<td>{{load.load_number}}</td>
<td>{{load.load_status}}</td>
<td>{{load.agent}}</td>
<td>{{user.customer.company_name}}</td>
<td>{{load.carrier}}</td>
<td>{{load.pickup_date}}</td>
<td>{{load.delivery_date}}</td>
<td>{{load.shipper}}</td>
<td>{{load.consignee}}</td>
<td>{{load.po_number}}</td>
<td>{{load.pu_number}}</td>
<td>{{load.date_created}}</td>
<td>
<a href="#">
<button class="btn btn-warning" type="button">
<span class="glyphicon glyphicon-pencil"></span> </button>
</a>
<a href="#">
<button class="btn btn-danger" type="button">
<span class="glyphicon glyphicon-remove"></span> </button>
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>

You don't need a custom model manager for those queries at all. You can accomplish this sending the loads grouped by status to the template:
class LoadListView(ListView):
# ...
def get_context_data(self, **kwargs):
context = super(LoadListView, self).get_context_data(**kwargs)
statuses = (choice[0] for choice in Load.LOAD_STATUS_CHOICES)
context['loads_by_status'] = {
status: Load.objects.filter(load_status=status) for status in statuses
}
return context
Template:
{% for status, loads in loads_by_status.items %}
<h4>Status: {{ status }}</h4>
<table>
<thead>
<tr>
<th>Load number</th>
...
</tr>
</thead>
<tbody>
{# remember, loads is a queryset at this point #}
{% for load in loads %}
<tr>
<td>{{ load.load_number }}</td>
...
</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}

Related

How to display items on html table from django model base on its category

I have items in a Stock model and each item has a category that it belongs to. I want it to iterate through the Stock model, find the distinct category, display the items that relate to that category, and display the category name as a caption above the related items on the table.
model.py
class Stock(models.Model):
user = models.ForeignKey(User, on_delete = models.SET_NULL, null = True)
part_No = models.CharField(max_length=100, null=True)
item_name = models.CharField(max_length=100, null=True)
category = models.CharField(max_length=100, null=True)
unit = models.CharField(max_length=50, null=True)
balance_bd = models.IntegerField(default='0', null = True)
received = models.IntegerField(default='0', null = True)
issued = models.IntegerField(default='0', null=True)
unit_price = models.DecimalField(max_digits=20, decimal_places=2, null=True)
obsolete = models.BooleanField(default=False, null=True)
views.py
def stock(request):
stocks = Stock.objects.all()
context = {
'stocks':stocks,
}
return render(request, 'base/stock.html', context)
html template
<!-- DATA TABLE-->
<div class="table-responsive m-b-40">
<table class="table table-borderless table-data3">
<thead>
<tr class="bg-primary">
<th>NO</th>
<th>PART NO</th>
<th>DESCRIPTION</th>
<th>CATEGORY</th>
<th>UNIT</th>
<th>BALANCE B/D</th>
<th>RECEIVED</th>
<th>TOTAL BAL</th>
<th>ISSUED</th>
<th>TALLY CARD BAL</th>
<th>UNIT PRICE</th>
<th>TOTAL PRICE</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
{% for stock in stocks %}
{% if stock.obsolete %}
<tr>
<td>{{forloop.counter}}</td>
<td class="text-success"><i>{{stock.part_No}}</i></td>
<td class="text-success"><i>{{stock.item_name}}(obsolete)</i></td>
<td class="text-success"><i>{{stock.category}}</i></td>
<td class="text-success"><i>{{stock.unit}}</i></td>
<td class="text-success"><i>{{stock.balance_bd}}</i></td>
<td class="text-success"><i>{{stock.received}}</i></td>
<td class="text-success"><i>{{stock.total_bal}}</i></td>
<td class="text-success"><i>{{stock.issued}}</i></td>
<td class="text-success"><i>{{stock.tally_card_bal}}</i></td>
<td class="text-success"><i>{{stock.unit_price}}</i></td>
<td class="text-success"><i>¢{{stock.total_price}}</i></td>
<td>
<div class="table-data-feature">
<a href="{% url 'update-item' stock.id %}"> <button class="item" data-toggle="tooltip" data-placement="top" title="Update">
<i class="zmdi zmdi-edit"></i>
</button></a>
<button class="item" data-toggle="tooltip" data-placement="top" title="Delete">
<i class="zmdi zmdi-delete"></i>
</button>
</div>
</td>
</tr>
{% else %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{stock.part_No}}</td>
<td>{{stock.item_name}}</td>
<td>{{stock.category}}</td>
<td>{{stock.unit}}</td>
<td>{{stock.balance_bd}}</td>
<td>{{stock.received}}</td>
<td>{{stock.total_bal}}</td>
<td>{{stock.issued}}</td>
<td>{{stock.tally_card_bal}}</td>
<td>¢{{stock.unit_price}}</td>
<td>¢{{stock.total_price}}</td>
<td>
<div class="table-data-feature">
<a href="{% url 'update-item' stock.id %}"> <button class="item" data-toggle="tooltip" data-placement="top" title="update">
<i class="zmdi zmdi-edit"></i>
</button></a>
<button class="item" data-toggle="tooltip" data-placement="top" title="Delete">
<i class="zmdi zmdi-delete"></i>
</button>
</div>
</td>
</tr>
{% endif %}
{% empty %}
<p>No item in stock</p>
{% endfor %}
<tr>
<td></td>
<td></td>
<td></td>
<td colspan="8" style="font-weight: bold;">TOTAL PRICE</td>
<td class="text-success" style="font-weight: bold;">¢{{sumTotalPrice}}</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<!-- END DATA TABLE-->
These is the results I have so far
my stock table
And I want it to look like this image
Django Provided regoup template tag you can easily understand from Django official documentation
Link is here

How to merge two Querysets and create new queryset in django

I have two models for two parts of AC, that is IndoorInventory for the indoor unit which shows all indoor unit information, and OutdoorInventory for showing outdoor unit information.
class IndoorInventory(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
product = models.CharField(max_length=50)
indoor_brand = models.CharField(max_length=100, null=True, blank=True)
indoor_model_no = models.CharField(max_length=100, null=True, blank=True)
indoor_sr_no = models.CharField(max_length=100, null=True, blank=True)
outdoor_model_no = models.CharField(max_length=100, null=True, blank=True)
class OutdoorInventory(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
product = models.CharField(max_length=50)
outdoor_brand = models.CharField(max_length=100, null=True, blank=True)
outdoor_model_no= models.CharField(max_length=100, null=True, blank=True)
outdoor_sr_no = models.CharField(max_length=100, null=True, blank=True)
indoor_model_no= models.CharField(max_length=100, null=True, blank=True)
I am passing a queryset of IndoorInventory to my Django template and fetching all the data there. Below is my VIEW
def clientInventory(request):
context = {}
client_id = request.GET.get('client_id')
id_inven = IndoorInventory.objects.filter(client=client_id)
od_inven = OutdoorInventory.objects.filter(client=client_id)
context['id_inven'] = id_inven
return render(request, 'client-inventory.html', context)
My Template Below
<table id="client-invent-admin" class="table table-striped table-bordered display nowrap">
<thead>
<tr>
<th class="filterhead">ID</th>
<th class="filterhead">Brand</th>
<th class="filterhead">Product/Type</th>
<th class="filterhead">ID Model No</th>
<th class="filterhead">ID SR No</th>
<th class="filterhead">OD Model No</th>
<th class="filterhead">Actions</th>
</tr>
<tr>
<th>ID</th>
<th>Brand</th>
<th>Product/Type</th>
<th>ID Model No</th>
<th>ID SR No</th>
<th>OD Model No</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for invent in id_inven %}
{% if invent.indoor_model_no == '' %}
<tr class="bg-danger">
<td>{{ invent.id }}</td>
<td>{{ invent.indoor_brand }}</td>
<td>{{ invent.product }}</td>
<td>{{ invent.indoor_model_no }}</td>
<td>{{ invent.indoor_sr_no }}</td>
<td>{{ invent.outdoor_model_no }}</td>
<td>
<div class="dropdown icon-dropdown">
<a class="btn-icon dropdown-toggle" data-toggle="dropdown" href="#">
<i class="zmdi zmdi-more"></i>
</a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#"><i class="feather icon-eye"></i> View</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#"><i class="feather icon-edit"></i> Edit</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item"
href="/delClient-invent/?invent_id={{invent.id}}&client_id={{client_id}}">
<i class="feather icon-trash"></i> Delete
</a>
</div>
</div>
</td>
</tr>
{% else %}
<tr>
<td>{{ invent.id }}</td>
<td>{{ invent.indoor_brand }}</td>
<td>{{ invent.product }}</td>
<td>{{ invent.indoor_model_no }}</td>
<td>{{ invent.indoor_sr_no }}</td>
<td>{{ invent.outdoor_model_no }}</td>
<td>
<div class="dropdown icon-dropdown">
<a class="btn-icon dropdown-toggle" data-toggle="dropdown" href="#">
<i class="zmdi zmdi-more"></i>
</a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#"><i class="feather icon-eye"></i> View</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#"><i class="feather icon-edit"></i> Edit</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item"
href="/delClient-invent/?invent_id={{invent.id}}&client_id={{client_id}}">
<i class="feather icon-trash"></i> Delete
</a>
</div>
</div>
</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Brand</th>
<th>Product/Type</th>
<th>ID Model No</th>
<th>ID SR No</th>
<th>OD Model No</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
See table frontend
Now I want to get the outdoor_sr_no from OutdoorInventory models and pass it to the IndoorInventory Queryset so that the outdoor_sr_no value also get fetched on the table next to (OD model no) column in the table
You can use the chain method which concatenates the querysets
from itertools import chain
result_list = list(chain(q1, q2, q*))
The chain method returns a chained object, so you transform it into a list and then you can get the information.
You can also use the union method (Django Union Method)
qs1.union(qs2)
See more information in How can I combine two or more querysets in a Django view?
In your clientInventory method, you could add od_inven to your context dict.
context['id_inven'] = id_inven
context['od_inven'] = od_inven
Then you could use that in your template in the same way you are currently using id_inven. Something like:
...
<body>
{% for foo in od_inven %}
...
<td>{{ foo.id }}</td>
...

Django Edit Or Delete Selected Rows In A Table - ListView

I have a table with checkboxes and I would like to be able to delete or edit a specific field value for all the selected rows in the table.
Here's an example table that would be awesome to recreate but I have not found examples anywhere how this may work in the view and template. https://examples.bootstrap-table.com/#
My current view, which is working with a table. Where can I start to make the leap from a basic table to an interactive one like in the example above?
Views.py
class EntryList(LoginRequiredMixin, ListView):
context_object_name = 'entry_list'
paginate_by = 100
# paginate_by = 5
#ordering = ['-pk']
model = Entry
template_name = "portfolios/entry_list.html"
def get_queryset(self):
return Entry.objects.filter(created_by=self.request.user).order_by('-pk')
def post(self, request, *args, **kwargs):
ids = self.request.POST.get('ids', "")
# ids if string like "1,2,3,4"
ids = ids.split(",")
try:
# Check ids are valid numbers
ids = map(int, ids)
except ValueError as e:
return JsonResponse(status=400)
# delete items
self.model.objects.filter(id__in=ids).delete()
return JsonResponse({"status": "ok"}, status=204)
entry_list.html
{% extends "dashboard/base.html" %}
{% load i18n %}
{% block content %}
<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h2 class="text-gray-800">{% block title %}{% trans "Imported Entries" %}{% endblock %}</h2>
<a role="button" class="btn btn-success" href="{% url 'import' %}"><i
class="fas fa-plus-circle"></i> Import New Entires</a>
</div>
<!-- Content Row -->
<div class="row">
<div class="col-md-12">
<div class="card shadow mb-4">
<div class="card-body">
<div id="dataTable_wrapper" class="dataTables_wrapper dt-bootstrap4">
<div class="row">
</div>
<div class="row">
<div class="col-sm-12">
<table class="table-responsive-xl table table-hover table-striped table-bordered dataTable" id="dataTable" width="100%"
cellspacing="0" role="grid" aria-describedby="dataTable_info">
<thead>
<tr role="row">
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">ID
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Date
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Trade
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Type
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Symbol
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Amount
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Price
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Fee
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Reg Fee
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Ref
</th>
</tr>
</thead>
<tbody>
{% for entry in object_list %}
<tr role="row">
<td class="text-center">
<div class="custom-control-lg custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input form-control-lg" data-id="{{ entry.pk}}" id="check{{ entry.pk }}">
<label class="custom-control-label" for="check{{ entry.pk }}"></label>
</div>
</td>
<td>{{ entry.pk }}</td>
<td>{{ entry.date | date:"M d, Y h:i:s A"}}</td>
<td>{{ entry.trade.id }}</td>
<td>{{ entry.entry_type }}</td>
<td>{{ entry.symbol }}</td>
<td>{{ entry.amount }}</td>
<td>{{ entry.price }}</td>
<td>{{ entry.fee }}</td>
<td>{{ entry.reg_fee }}</td>
<td>{{ entry.transaction_id }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<!--Pagination-->
<div class="row">
<div class="col-12 ">
<div class="pagination">
<span class="step-links">
{% if page_obj.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
next
last »
{% endif %}
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
It depends on how you've implemented your frontend, but assuming you have standard django templates, then I would suggest taking a look at datatables. There's quite a lot to it, but it is very stable and has a decent feature set, and the documentation is good. You can style it how you want using bootstrap.
Also, you link to Bootstrap Table - that should be the same principle. Read through the docs to understand how it works, and you will have to use Django template tags to render the data in the table.
Note that the table is implemented using HTML / Jquery, so it is not directly related to Django. All you need to do is to iterate over the django objects in your template (example)
EDIT
How to delete a selected row?
Suppose you could select N rows, and then click a button to delete all of these rows.
This could work as follows:
Add a handler to the delete button:
identify the selected rows
send an Ajax request to delete the rows
handle the success response to remove the deleted rows from the table
// SIMPLIFIED CODE SAMPLE
$("#delete-btn").click(function () {
var selectedRows = table.rows({"selected": true});
var dataObj = {
// parse selectedRows to get object ids
}
$.ajax({
url: '/api/delete-rows/',
type: 'post',
data: dataObj,
success: function (data, status, xhr) {
// remove the selected rows from the view
table.rows({"selected": true}).deselect().remove().draw();
}
})
}
How to select rows and quickly change a field for all of the selected rows?
The same principle here. Once rows are selected, have a handler which identifies the selected rows, then you can use the datatables api to update given fields (docs).

How to persist data found in tables within a django template, in postgresql

I am scraping several sites and I show the data obtained in 6 tables within a django template.
My intention is to persist the data of the tables in postgresql, but I can not realize how to perform that task.
In principle I am trying to save the data from the second table.
For this I have created the models that I show below, as well as a view that is called: registroDivisaArgentina ().
The template is called quotes.html and within it, there are 6 tables.
I have tried to work with a class called: RegisterArgentineValues () within a forms.py file
models.py
class DivisasArgentina(models.Model):
class Meta:
ordering = ['CodigoDA']
CodigoDA = models.CharField(max_length=50, primary_key = True)
Texto_para_Reporte = models.CharField(max_length=70)
def __str__(self):
return '{}'.format(self.Texto_para_Reporte)
class ValoresDivisasArgentina(models.Model):
class Meta:
ordering = ['Dia']
DivisasArgentina = models.ForeignKey(DivisasArgentina, on_delete=models.PROTECT)
Dia = models.DateField(default=date.today)
Hora = models.DateTimeField(default=timezone.now)
Compra = models.FloatField()
Venta = models.FloatField()
Variacion_dia_anterior = models.FloatField()
ClaveComparacion = models.CharField(max_length=1)
def __str__(self):
return '{} - {} - {}'.format(self.DivisasArgentina, self.Dia, self.ClaveComparacion)
cotizaciones.html
{% extends 'base.html' %}
{% block contenido %}
<form method="POST" class="post-form">{% csrf_token %}
<div class="container">
<table class="table table-striped table-bordered" id="tab1">
<thead>
<tr>
<th>Divisas en el Mundo</th>
<th>Valor</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_mun%}
<tr>
{% for key,value in element.items %}
<td> {{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
</table>
</div>
<div class="container">
<table class="table table-striped table-bordered" id="tab2">
<thead>
<tr>
<th>Divisas en Argentina</th>
<th>Compra</th>
<th>Venta</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_arg%}
<tr>
{% for key,value in element.items %}
<td>{{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
<thead>
{{ form.as_table }}
</table>
</div>
<div class="container">
<table class="table table-striped table-bordered" id="tab3">
<thead>
<tr>
<th>Dolar Banco Nacion Argentina (Divisas)</th>
<th>Compra</th>
<th>Venta</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_exp%}
<tr>
{% for key,value in element.items %}
<td>{{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab4">
<thead>
<tr>
<th colspan="4">Dolar Futuro en Argentina</th>
</tr>
<tr>
<th>Mes 1</th>
<th>Mes 2</th>
<th>Mes 3</th>
<th>Mes 4</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_dol%}
<td>
{{ element.Valores}}
</td>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab5">
<thead>
<tr>
<th colspan="3">Indicadores Varios - Tasa Libor</th>
</tr>
<tr>
<th>Libor a 1 Mes</th>
<th>Libor a 2 Mes</th>
<th>Libor a 3 Mes</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_lib%}
<td>
{{ element.Valores }}
</td>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab6">
<thead>
<tr>
<th>Indicadores Varios - Indice Merval y Oro</th>
<th>Valores</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_ind%}
<tr>
{% for key,value in element.items %}
<td> {{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tr>
</tbody>
</table>
</div>
<div class="container" id="saveData">
<br></br>
<button type="submit" class="btn btn-primary pull-right">Guardar Datos</button>
</div>
</form>
{% endblock %}
views.py
def mostrar_cotizaciones(request):
cotiz_arg = json.loads(j_cotizaciones_argentina)
cotiz_mun = json.loads(j_cotizaciones_mundiales)
cotiz_exp = json.loads(j_cotizacion_export)
cotiz_dol = json.loads(j_dolar_futuro)
cotiz_ind = json.loads(j_indicadores)
cotiz_lib = json.loads(j_libor)
context = {'cotiz_mun': cotiz_mun,
'cotiz_arg': cotiz_arg,
'cotiz_exp': cotiz_exp,
'cotiz_dol': cotiz_dol,
'cotiz_ind': cotiz_ind,
'cotiz_lib': cotiz_lib,
}
return render(request, 'cotizaciones.html', context)
def registrarDivisaArgentina(request):
if request.method == 'POST':
formulario = RegistrarValoresDivisasArgentinas(request.POST)
if formulario.is_valid():
formulario.save()
return HttpResponseRedirect('/listadoValores')
else:
formulario = RegistrarValoresDivisasArgentinas()
formulario.setup('Registrar', css_class="btn btn-success")
return render(request, 'cotizaciones.html', {'formulario':formulario})
forms.py
from django import fla
from django.forms import ModelForm
from django import forms
from fla.models import *
class RegistrarValoresDivisasArgentinas(forms.ModelForm):
class Meta:
model = ValoresDivisasArgentina
fields= [Compra, Venta]
I have done some tests, but none has given a favorable result. Someone can tell me how to process the data (in the views and forms) that are in the tables, to be able to store them in my postgres tables ?
I do this kind of task very often, and I've found out that the combination of ScraPy with scrapy-djangoitem is a very good combo to use here.
Good luck!

How do I get a list of the categories column, and then list of everything in a single view?

I want a navbar on top of my page with the categories in my model.
And when I click on the link to a category, I want a table that lists the items in that category.
For whatever reason I just can't get both things to work at the same time.
This is my model
from django.db import models
# Create your models here.
class menulist(models.Model):
name = models.CharField(max_length=120)
description = models.CharField(max_length=500)
price = models.DecimalField(decimal_places=1, max_digits=10, default=100.00)
category_choices = (
('breads', 'Breads'),
('cakes', 'Cakes'),
('hotfood', 'Hot Food'),
('porkrolls', 'Pork Rolls'),
('drinks', 'Drinks'),
('MISC', 'Misc'),
)
category = models.CharField(max_length=50, choices=category_choices, default='MISC',)
dateadded = models.DateField(auto_now_add=True)
dateupdated = models.DateField(auto_now=True)
img = models.ImageField(upload_to='products/', default='products/blank.jpg')
def __str__(self):
return self.name
This is the view:
class ProductAdminView(ListView):
template_name = 'menulistapp/product_admin.html'
def get_context_data(self, *, object_list=None, **kwargs):
context = super(ProductAdminView, self).get_context_data(**kwargs)
categorylist = menulist._meta.get_field('category').choices
context = {
"category_list": categorylist,
}
return context
def get_queryset(self):
slug = self.kwargs.get("slug")
if slug:
queryset = menulist.objects.filter(category__iexact=slug)
else:
queryset = menulist.objects.all()
return queryset
html template:
{% extends 'base.html' %}
{% block content %}
<div class="container ">
<ul class="nav nav-pills border-bottom border-top pt-2 pb-2">
{% for a, b in category_list %}
<li class="nav-item">
<a class="nav-link" href="/productadmin/{{ a }}">{{ b }}</a>
</li>
{% endfor %}
</ul>
</div>
<!-- tables -->
<div class="container">
<div class="row">
<table class="table table-striped table-hover ">
<thead class="thead-dark">
<tr>
<th style="width: 15%"scope="col"></th>
<th style="width: 55%" scope="col">Product Name</th>
<th scope="col">Category</th>
<th scope="col">Price</th>
<th scope="col">Date Added</th>
<th scope="col">Last Updated</th>
</tr>
</thead>
<tbody>
{% for obj in object_list %}
<tr>
<td class="align-middle"><img src="{{ obj.img.url }}" class="img-fluid"></td>
<td class="align-middle">{{ obj }}</td>
<td class="align-middle">{{ obj.category }}</td>
<td class="align-middle">${{ obj.price }}</td>
<td class="align-middle">{{ obj.dateadded }}</td>
<td class="align-middle">{{ obj.dateupdated }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
Sometimes I can only get the list working if I comment out the nav bar, and vice versa.
I've looked at mixins, but that only confused me more and doesn't do anything.