Django Model Method access from template - django-models

I cannot render in a template the method get_total_hoy, what it does is get the total sales of products of the currrent day;
class VentaProductos(models.Model):
producto = models.ForeignKey(
Productos, null= True, on_delete=models.SET_NULL)
medio_de_venta = models.ForeignKey(MediosVenta, null=True, blank=False, on_delete=models.SET_NULL)
precio_de_venta = models.FloatField(null=True, blank=True)
fecha_venta = models.DateField(blank=False, null=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
vendido_por = models.CharField(max_length=20, null=False, blank=False)
class Meta:
verbose_name_plural = "Venta de Productos"
ordering = ["-id"]
def __str__(self):
return f"{self.producto.nombre}"
def get_total_hoy(self):
today = timezone.now()
total = VentaProductos.objects.filter(fecha_venta=today).aggregate(total = Sum('precio_de_venta'))
total_productos = total['total']
print(total_productos)
return total_productos
in my template I have the following table:
<h2>Ventas de hoy</h2>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Nombre</th>
<th scope="col">Precio</th>
<th scope="col">Fecha</th>
<th scope="col">vendido por</th>
</tr>
</thead>
<tbody>
{% for producto in ventaproductos_list %}
<tr>
<th scope="row">{{forloop.counter}}</th>
<td>{{producto.producto}}</td>
<td>${{producto.precio_de_venta}}</td>
<td>{{producto.fecha_venta}}</td>
<td>{{producto.vendido_por}}</td>
</tr>
{% endfor %}
<tr>
<td>${{ventaproductos.get_total_hoy}}</td>
</tr>
</tbody>
</table>
I'm trying to display that total at the end of the table.
My understanding is that if my method does not required extra parameters there is no need to access it as context in the view and I can access directly. Anyway I this is my current view (if it helps):
class Home(ListView):
model = VentaProductos
template_name= 'main/home.html'
def get_queryset(self):
today = timezone.now()
return VentaProductos.objects.filter(fecha_venta = today)

Related

How to generate a table on select of a dropdown in Angular 8

In my program, I've the table already rendered with all the given possible values. I only want to retrieve the values matching with my bookingId in the table.
*view.component.ts
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { Booking } from '../booking.model';
import { ViewService } from './view.service';
#Component({
selector: 'app-view-component',
templateUrl: './view-component.component.html',
styleUrls: ['./view-component.component.css']
})
export class ViewComponentComponent implements OnInit {
bookings=[];
selected: number;
tableData:any[];
selectedId:string='';
constructor(private http: HttpClient, private view: ViewService) { }
ngOnInit(): void {
this.getBookings();
}
getBookings(): void {
this.view.getBookings()
.subscribe((data:any) => {
this.bookings = data;
console.log(this.bookings);
});
}
onSelected(value:string){
console.log("the selected value is " + value);
let temp =this.bookings.filter(el=>el.bookingId===value)
console.log(temp);
this.bookings=temp
}
}
view.component.html
<label for="bookings">
Select a Booking Id
</label>
<select class="form-control" id="bookings" #mySelect
(change)='onSelected(mySelect.value)'>
<option disabled selected value="">Select an Id</option>
<option *ngFor="let book of bookings" [value]="book.bookingId">
{{book.bookingId}}
</option>
</select>
<table class="table table-striped" >
<thead>
<tr>
<th>Booking Id</th>
<th>First Name</th>
<th>Gender</th>
<th>Category</th>
<th>Booking Date</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let book of bookings">
<td>{{book.bookingId}}</td>
<td>{{book.guestName}}</td>
<td>{{book.gender}}</td>
<td>{{book.categoryName}}</td>
<td>{{book.bookingDate| date: 'dd/MM/yyyy'}}</td>
</tr>
</tbody>
</table>
The problem is the table is already generated by the time my application loads. I want it to generate on select of the appropriate dropdown. The dropdown is populated by Booking Ids. Can someone give a solution
You binding same array in HTML use another empty array for filter data.
if you want first booking id data loaded when page render then just call onSelected(data[0].bookingId) after get data in getBookings()
filtersBookings = [];
onSelected(value:string){
this.filtersBookings =this.bookings.filter(el=>el.bookingId===value)
}
<tr *ngFor="let book of filtersBookings">
<td>{{book.bookingId}}</td>
<td>{{book.guestName}}</td>
<td>{{book.gender}}</td>
<td>{{book.categoryName}}</td>
<td>{{book.bookingDate| date: 'dd/MM/yyyy'}}</td>
</tr>
You should not load booking in ngOnInit hook, you should load it in your onSelected event handler,
and in your template, you can your the ngIf to load your table only when there is booking like the following
<table class="table table-striped" *ngIf="bookings.length>0">
<thead>
<tr>
<th>Booking Id</th>
<th>First Name</th>
<th>Gender</th>
<th>Category</th>
<th>Booking Date</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let book of bookings">
<td>{{book.bookingId}}</td>
<td>{{book.guestName}}</td>
<td>{{book.gender}}</td>
<td>{{book.categoryName}}</td>
<td>{{book.bookingDate| date: 'dd/MM/yyyy'}}</td>
</tr>
</tbody>
</table>

how to calculate the number of days left in laravel for all raws from database

Dears,
Iam trying to create a laravel based project, In that i have a section to show the days remaining in... I have 3 coloums in my db they are
sub_start_date (which means the subscription start date)
sub_end_date(which means the subscription end date)
subscription_type(It should be a select box in that 1 month,2 month
and 3 month accordingly).
In that the sub_end_date is calculated automatically with the help of jQuery. So it will be stored in the db As 1-9-2020 (M-D-Y).
So My problem is i cannot count the days remaining.. i have googled and get somewhat similar solution that i will add below but its only for one row(or for the row that we will add at the last )And in my blade.php page it was showing the same result in a loop..
//subscription_details.blade.php
#extends('layouts.app')
#section('body')
<center>
</br>
<div class="col-lg-5">
<h4>subscribtion details</h4></br>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Phone Number</th>
<th scope="col">Type Of Subscription</th>
<th scope="col">Start Date</th>
<th scope="col">End Date</th>
<th scope="col">Days Remaining</th>
</tr>
</thead>
<tbody>
<tr>
#foreach($customer as $row)
<th scope="row">{{$row->name}}</th>
<td>{{$row->phone}}</td>
<td>{{$row->subscription}}Month</td>
<td>{{$row->sub_start_date}}</td>
<td>{{$row->sub_end_date}}</td>
<td>{{$count}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</center>
#endsection
My controller code is
//SubscriptionController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\customer;
use Carbon\Carbon ;
class SubscriptionController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$now = Carbon::now();
$customer =customer::all();
foreach($customer as $row)
{
$end_date = $row->sub_end_date;
$cDate = Carbon::parse($end_date);
$count = $now->diffInDays($cDate );
}
return view('subscription_details',compact('customer','count'));
}
As of now iam getting this
subscribtion details
results are like
Sub_start date = 2019-12-01 ,Sub_end date =2019-12-01 days remaining is 260 days for every coloum
please help me to find a solution
Defined a mutator attribute in your customer model:
use Carbon\Carbon;
...
public function getRemainingDaysAttribute()
{
if ($this->sub_end_date) {
$remaining_days = Carbon::now()->diffInDays(Carbon::parse($this->sub_end_date));
} else {
$remaining_days = 0;
}
return $remaining_days;
}
And In your controller, just take your customers:
public function index()
{
$customer =customer::all();
return view('subscription_details',compact('customer'));
}
And In your view:
#foreach($customer as $row)
<th scope="row">{{$row->name}}</th>
<td>{{$row->phone}}</td>
<td>{{$row->subscription}}Month</td>
<td>{{$row->sub_start_date}}</td>
<td>{{$row->sub_end_date}}</td>
<td>{{$row->remaining_days}}</td>
</tr>
#endforeach

Angularjs how can i add record in Table using array

$scope.JobData = [];
$scope.SaveData = function (MyData) {
debugger;
var _data = [];
_data = {
fname: MyData.fname,
mname: MyData.Mname,
}
$scope.JobData.push(_data).toString();
}
This is my Table
<table class="">
<thead>
<tr>
<th>First Name</th>
<th>Middle Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="_mydata in JobData">
<td>{{_mydata.fname}}</td>
<td>{{_mydata.Mname}}</td>
</tr>
</tbody>
Here how can i appemded my data to the table. Here my intension is add bulk upload
what ever the code you had written is well and good but ur asssign name are not matching with ur table table please see this
_data = {
fname: MyData.fname,
Mname: MyData.Mname,
Lname: MyData.Lname
}
now i hope its work

Using stored procedure to retrieve data from database

I'm using a stored procedure to pull a list of items from a database however I keep getting this error:
Procedure or function 'requisition_sp_getItemNum' expects parameter '#reqNumber', which was not supplied.
I have use the hiddenfor in order to supply the reqNumber but that throws the same error message
Stored procedure:
ALTER PROCEDURE [dbo].[requisition_sp_getItemNum]
#reqNumber VARCHAR(50)
AS
BEGIN
SELECT
a.ITEMNMBR, a.ITEMDESC, ab.employee_id,
ab.department, ab.employee_name, quantity_requested,
b.expense_acc, c.ACTDESCR + '/' + c.ACTNUMBR_1 + '-' + c.ACTNUMBR_2 [Expense_Acc],
b.unit_of_measure
FROM
[TWCL].[dbo].IV00101 a
INNER JOIN
RequisitionItem b ON a.ITEMNMBR = b.item_no
INNER JOIN
Requisition ab ON ab.Req_No = b.Req_No
INNER JOIN
[TWCL].dbo.GL00100 c ON b.expense_acc = c.ACTINDX
WHERE
b.Req_No = #reqNumber AND ab.status = -1
END
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<hr/>
<table id="data">
<thead>
<tr>
<th></th>
<th >#Html.CheckBox("TheOneCheckBoxToRuleThemAll")Select All</th>
<th class="col-lg-1 ">Date</th>
<th class="col-lg-1 ">Requisition Number</th>
<th class="col-lg-1 ">Expense Account</th>
<th class="col-lg-1">Requestor</th>
<th class="col-lg-1">Department</th>
<th class="col-lg-1">LoggedinAs</th>
<th class="col-lg-1 ">Item Number</th>
<th class="col-lg-1 ">Description</th>
<th class="col-sm-1">Quantity</th>
<th class="col-sm-1 ">UOM</th>
</tr>
<tbody>
#for (int i = 0; i < Model.Count; i++)
{
foreach (var item in Model[i].items)
{
#Html.HiddenFor(m => m[i].reqNumber)
<tr>
<td>#Html.HiddenFor(m => m[i].reqNumber)</td>
<td>#Html.CheckBoxFor(m => m[i].postTrnx, new { #class = "checkGroup1" })</td>
<td class="col-lg-1 tabledata" >#Html.DisplayFor(m => m[i].reqDate)</td>
<td class="col-lg-1 tabledata" >#Html.DisplayFor(m => m[i].reqNumber)</td>
<td class="col-lg-1 tabledata">#item.expense_account.account_desc</td>
<td class="col-lg-1 tabledata">#item.employeeDetails.employeeNum</td>
<td class="col-lg-1 tabledata">#item.employeeDetails.department</td>
<td class="col-lg-1 tabledata">#item.employeeDetails.LoggedInUserName</td>
<td class="col-lg-1 tabledata">#item.itemNumber</td>
<td class="col-lg-1 tabledata">#item.description</td>
<td class="col-sm-1 tabledata">#item.quantity</td>
<td class="col-sm-1 tabledata">#item.selecteduomtext </td>
#*<td>#Html.ActionLink("Edit", "Edit", new { id = #item.lineNum, name = Model[i].reqNumber })</td>*#
</tr>
}
}
</tbody>
</table>
Model
public List<Item> getRequestItemByRquisition(string reqNumber)
{
List<Item> items = new List<Item>();
SqlConnection TWCLOPConnect = new SqlConnection(connectionString.ToString());
SqlCommand itemscommand = new SqlCommand();
SqlDataReader itemRdr;
itemscommand.CommandText = "requisition_sp_getItemNum ";
itemscommand.CommandType = CommandType.StoredProcedure;
itemscommand.Connection = TWCLOPConnect;
itemscommand.Parameters.Add("#reqNumber", SqlDbType.VarChar).Value = reqNumber;
try
{
TWCLOPConnect.Open();
itemRdr = itemscommand.ExecuteReader();
while (itemRdr.Read())
{
Item item = new Item();
item.itemNumber = itemRdr.GetString(0);
item.description = itemRdr.GetString(1);
item.employeeDetails.employeeNum = Convert.ToInt32(itemRdr.GetString(2));
item.employeeDetails.department = itemRdr.GetString(3);
item.employeeDetails.LoggedInUserName = itemRdr.GetString(4);
item.quantity = Convert.ToDouble(itemRdr[5]);
item.expense_account.index = itemRdr.GetInt32(6);
item.expense_account.account_desc = itemRdr.GetString(7);
item.selecteduomtext = itemRdr.GetString(8);
items.Add(item);
}
itemRdr.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
TWCLOPConnect.Close();
}
return items;
}
You variable from stored procedure #reqNumber:
#reqNumber varchar (50)
and the variable #Req_No you added here
itemscommand.Parameters.Add("#Req_No", SqlDbType.VarChar).Value = Req_No;
must match.
Change this:
itemscommand.Parameters.Add("#reqNumber", SqlDbType.VarChar).Value = reqNumber;
to this:
itemscommand.Parameters.Add("#reqNumber", reqNumber);
New way: can you change your code to this
SqlConnection TWCLOPConnect = new SqlConnection(connectionString.ToString());
SqlCommand itemscommand = new SqlCommand("requisition_sp_getItemNum", TWCLOPConnect);
itemscommand.CommandType = CommandType.StoredProcedure;
itemscommand.Parameters.Add("#reqNumber", reqNumber);
SqlDataReader itemRdr;
try
{
}

Angular/Datables server-side processing

I am trying to implement DataTables server-side processing/pagination for a table in angularjs. I have used the DataTables example but my table does not show. I am pretty sure I am missing one slight thing but can't figure it out....tried many things....
My HTML:
<div class="table-responsive">
<table id="consolidatedPageTable" class="table table-condensed table-striped table-bordered" >
<thead>
<tr>
<th >Source</th>
<th >Mailing Date</th>
<th >Status</th>
<th >CPI</th>
<th >User ID</th>
<th >Program</th>
<th >Customer Number</th>
<th >Customer Name</th>
<th >DL Date</th>
</tr>
</thead>
</table>
My controller:
app.controller('ConsolidatedController', function($scope,$rootScope,$http,$filter,$location,$routeParams) {
createTable();
$location.path('consolidated');
});
function createTable(){
$(function(){
var table = $('#consolidatedPageTable').dataTable({
"destroy": true,
"processing": true,
"serverSide": true,
"ajax": "scripts/consolidationTable.php",
"columnDefs": [
{
"targets": [9],
"visible": false,
"searchable": true
}
]
});
})
}
My php scipt (I replaced server specific information with XXX)
<?php
error_reporting(0);
$table = "consolidated";
$primaryKey = "customerNumber";
$columns = array();
$columns[] = array('db' => 'source' , 'dt' => 0);
$columns[] = array("db"=>"mailingDate","dt"=>1);
$columns[] = array("db"=>"status","dt"=>2);
$columns[] = array("db"=>"cpi","dt"=>3);
$columns[] = array("db"=>"userId","dt"=>4);
$columns[] = array("db"=>"shorttext","dt"=>5);
$columns[] = array("db"=>"customerNumber","dt"=>6);
$columns[] = array("db"=>"customerName","dt"=>7);
$columns[] = array("db"=>"dlDate","dt"=>8);
$sql_details = array("user" => "XXX","pass" => "XXX","db" => "XXX","host" => "XXX");
require("ssp.class.php");
echo json_encode(SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns ));
?>
I can run the php script by itself and it displays the correct data in the format shown in the dataTables example. In my application though, on the screen all I get is the header line and it does not appear to be in a dataTables looking format.
Can anyone see what could be causing no data to show?
I beleive the "columnDefs" object should be an array:
I console logged this after using the DTColumnDefBuilder included in the angular-datatables package. I could be wrong - I am having some difficulty with DT as well.

Resources