I am new in Django.
I want to update the value in the database based on the order id. Therefore, every order id has different updates. But, i only can update the last item that i add to the order. And every previous orders that i have, will directly follow the update from the last item.
models.py
class OrderItem(models.Model):
Table_No = models.IntegerField(blank=False)
FoodId = models.TextField()
Item = models.TextField()
Qty = models.DecimalField(max_digits=5, decimal_places=0)
Price = models.DecimalField(max_digits=10, decimal_places=2)
TotalPrice = models.TextField()
Note = models.TextField(max_length=100, null=True)
OrderId = models.TextField(max_length=5, null=True)
FoodStatus = (
('1', 'Has been ordered'),
('2', 'cooked'),
('3', 'ready to be served'),
('4', 'done'),
)
food_status = models.CharField(max_length=50, choices=FoodStatus)
views.py
def kitchen_view(request):
chef_view = OrderItem.objects.all()
if request.method == "POST":
order_id = request.POST.get("OrderId")
status = OrderItem.objects.filter(OrderId=request.POST.get("OrderId"))
status.status1 = OrderItem.objects.update(food_status=request.POST.get("food_status"))
return render(request, 'restaurants/kitchen_page.html', {'chef_view': chef_view})
kitchen_page.html
<form action="#" method="post">
<style>
table, th, td {
border: 1px solid black;
}
</style>
{% csrf_token %}
{% for order in chef_view %}
<table width="800">
<tr>
<th width="800">Table Number</th>
<th width="800">Item</th>
<th width="800">Quantity</th>
<th width="800">Price</th>
<th width="800">Note</th>
<th width="800">Order Id</th>
<th width="800">Status</th>
</tr>
<tr>
<td width="800">{{ order.Table_No }}</td>
<td width="800">{{ order.Item }}</td>
<td width="800">{{ order.Qty }}</td>
<td width="800">{{ order.Price }}</td>
<td width="800">{{ order.Note }}</td>
<td width="800">{{ order.OrderId }}</td>
<td width="800">{{ order.food_status }}
<input type="text" name="food_status">
</tr>
</table>
{% endfor %}
<br><a href='' button onclick="myFunction()"><input type="submit" value="Change Status"></button>
</form>
The result should be able to update the food_status based on the order_id. Therefore, every order_id may have different food_status and show it to the template.
Anyone can help me to solve this problem? I really need the help to solve this issue. Really appreciate.
Ok so real problem is that your form is incorrect - you are not sending OrderId to view. Here's quickfix to it:
kitchen_page.html:
<style>
table, th, td {
border: 1px solid black;
}
</style>
<form action="#" method="post">
<table width="800">
<tr>
<th width="800">Table Number</th>
<th width="800">Item</th>
<th width="800">Quantity</th>
<th width="800">Price</th>
<th width="800">Note</th>
<th width="800">Order Id</th>
<th width="800">Status</th>
</tr>
{% csrf_token %}
{% for order in chef_view %}
<tr>
<td width="800">{{ order.Table_No }}</td>
<td width="800">{{ order.Item }}</td>
<td width="800">{{ order.Qty }}</td>
<td width="800">{{ order.Price }}</td>
<td width="800">{{ order.Note }}</td>
<td width="800">{{ order.OrderId }}</td>
<td width="800">{{ order.food_status }}
<input type="text" name="food_status" value="{{ order.food_status }}">
</tr>
<input type="hidden" name="OrderId" value="{{ order.OrderId }}">
{% endfor %}
</table>
<br><button type="submit" value="Change Status">Change Status</button>
</form>
views.py:
def kitchen_view(request):
if request.method == "POST":
order_ids = request.POST.getlist("OrderId")
food_statuses = request.POST.getlist("food_status")
for i in range(len(order_ids)):
OrderItem.objects.filter(OrderId=order_ids[i]).update(food_status=food_statuses[i])
chef_view = OrderItem.objects.all()
return render(request, 'restaurants/kitchen_page.html', {'chef_view': chef_view})
Previously stored filtered objects are not being updated as you have
status = OrderItem.objects.filter(OrderId=request.POST.get("OrderId"))
but when you are updating them, you should be updating the already filtered objects like
status = status.update(food_status=request.POST.get("food_status"))
Hope this helps.
You can update multiple objects at once including the filter in a single line as:
status = OrderItem.objects.filter(OrderId=request.POST.get("OrderId")).update(food_status=request.POST.get("food_status"))
The problem in your code:
status.status1 = OrderItem.objects.update(food_status=request.POST.get("food_status"))
was that you were not using the filter, instead you tried updating the status1 field(Can't see a status1 field in your model) using status.status1.
Related
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>
...
I have a template that contains one search button (this is for filtering the details based on option choose in the select) and a Next button (this is to move to next tab).
When the template loads for then i will search for projects from the select list and the result will be displayed in a table - which is working for me.
After the result is displayed in the table, i will select a row (through radio button) from that table and click on Next button to move to next tab. Here when i click the Next button i want to update some values in the django database but not able to achieve this. Can some one help me?
My View:
def form(request):
projects = CreateProjects.objects.filter(Status=True)
if request.method == 'POST':
selectproject = request.POST.get('selectproject')
searchprojlist = ListProjDetails.objects.filter(Project=selectproject)
return render(request,'form.html',{'projects':projects,'lists': searchprojlist})
elif request.POST.get('tab1btn','') == 'nxttab':
selval = ListProjDetails.objects.get(id=1)
selval.Selected = True
selval.LockedUser = request.user
selval.save()
else:
lists = ListProjDetails.objects.all()
return render(request,'form.html',{'projects':projects})
First If POST is working correctly, trouble is with the 2nd IF (2nd button). I have swapped the 2nd IF to be called fresh after the else statement but not working either.
I have passed id=1 for testing purpose only
enter image description here
I have added the image for better understanding, basically when the template loads select project from the list and Search and then choose one from the output and press next that moves to next tab by updating values like select to True and Locked User to current user.
My view as explained before.
My Javascript:
$(function(){
$('#nexttab').click(function(e){
e.preventDefault();
if(document.getElementById('selectradio').checked){
$('#tabs a[href="#tab2"]').tab('show');
}
});
})
Template:
<form method="POST">
{% csrf_token %}
<div class="row ml-auto">
<select class="custom-select mb-4 ml-2" name="selectproject" style="width: 30em;">
<option selected>Choose...</option>
{% for projects in projects %}
<option>{{ projects.ProjName}}</option>
{% endfor %}
</select>
<div class="ml-4">
<button type="submit" class="btn btn-primary" value="Search">Search</button>
</div>
</div>
<table class="table">
<thead class="thead-light">
<tr>
<th scope="col" class="text-center">S.No.</th>
<th scope="col" class="text-center">Project Name</th>
<th scope="col" class="text-center">Doc</th>
<th scope="col" class="text-center">Target Date</th>
<th scope="col" class="text-center">Docnum</th>
<th scope="col" class="text-center">Type</th>
<th scope="col" class="text-center">Select</th>
<th scope="col" class="text-center">Locked by User</th>
<th scope="col" class="text-center">Status</th>
</tr>
</thead>
<tbody>
{% for lists in lists %}
<tr>
<th scope="row" class="text-center">{{ lists.id }}</th>
<td class="text-center">{{ lists.Project }}</td>
<td class="text-center">{{ lists.doc }}</td>
<td class="text-center">{{ lists.TargetDate }}</td>
<td class="text-center">{{ lists.docnum }}</td>
<td class="text-center">{{ lists.type }}</td>
<td class="text-center"><input class="form-check-input" type="radio"
name="select1" id="selectradio" value="option1"></td>
<td class="text-center">{{ lists.LockedUser }}</td>
<td class="text-center">
{% if lists.DStatus == "Available" %}
<label class="badge badge-success">
{% else %}
<label class="badge badge-warning">
{% endif %}
{{ lists.DStatus }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="text-right mr-5">
<button type="submit" class="btn btn-primary" id="nexttab" name="tab1btn"
value="nxttab">Next</button>
</div>
</form>
I am just trying to re-factor your code, you should be able to pickup then.
from django.shortcuts import render, redirect
from django.urls import reverse
def form(request):
projects = CreateProjects.objects.filter(Status=True)
if request.method == 'POST':
if request.POST.get('tab1btn','') == 'nxttab':
selval = ListProjDetails.objects.get(id=1)
selval.Selected = True
selval.LockedUser = request.user
selval.save()
return redirect(reverse('name-of-the-view')) # redirect to form.html
selectproject = request.POST.get('selectproject')
searchprojlist = ListProjDetails.objects.filter(Project=selectproject)
return render(request,'form.html',{'projects':projects,'lists': searchprojlist})
else:
lists = ListProjDetails.objects.all()
return render(request,'form.html',{'projects':projects})
I am a newbie
I want to change selected data (food_status) and save it to selected column (food_status column). But it shows an error
for field in self._meta.concrete_fields:
AttributeError: 'NoneType' object has no attribute '_meta'
in this part
OrderItem.save(food_status, update_fields=['food_status'])
models.py
class OrderItem(models.Model):
Table_No = models.IntegerField(blank=False)
FoodId = models.TextField()
Item = models.TextField()
Qty = models.IntegerField(blank=False)
Price = models.TextField()
Note = models.TextField(max_length=100, null=True)
OrderId = models.TextField(max_length=100, null=True)
FoodStatus = (
('1', 'Has been ordered'),
('2', 'cooked'),
('3', 'ready to be served'),
('4', 'done'),
)
food_status = models.CharField(max_length=50, choices=FoodStatus,
default="has been ordered")
views.py
def kitchen_view(request):
chef_view = OrderItem.objects.all()
if request.method == "POST":
food_status = request.POST.get("food_status")
OrderItem.food_status = food_status
OrderItem.save(food_status, update_fields=['food_status'])
return render(request, 'restaurants/kitchen_page.html', {'chef_view':chef_view})
kitchen_page.html
<form action="#" method="post">
{% csrf_token %}
{% for order in chef_view %}
<table width="800">
<tr>
<th width="800">Table Number</th>
<th width="800">Item</th>
<th width="800">Quantity</th>
<th width="800">Price</th>
<th width="800">Note</th>
<th width="800">Order Id</th>
<th width="800">Status</th>
</tr>
<tr>
<td width="800">{{ order.Table_No }}</td>
<td width="800">{{ order.Item }}</td>
<td width="800">{{ order.Qty }}</td>
<td width="800">{{ order.Price }}</td>
<td width="800">{{ order.Note }}</td>
<td width="800">{{ order.OrderId }}</td>
<td width="800">{{ order.Status }}
<button type="button" class="close" data-dismiss="modal" aria-
label="Close"><span class="glyphicon glyphicon-pencil" aria-
hidden="true">×</span></button>
<select>
<option name="food_status" id="1" value="None">Has been
ordered</option>
<option name="food_status" id="2"
value="Cooked">Cooked</option>
<option name="food_status" id="3" value="Ready to be
served">Ready to be served</option>
<option name="food_status" id="4"
value="Done">Done</option>
</select>
<a href='' button onclick="myFunction()"><input
type="submit" value="Change Status"></button>
</td>
</tr>
</table>
{% endfor %}
</form>
The code should save the food_status to food_status database column based on the select option in html.
Anyone can help me? Really appreciate
You've almost got it, but just not quite in the right order. You can't do OrderItem.food_status = ... before creating an OrderItem instance. For example, this would work:
order_item = OrderItem()
order_item.food_status = food_status
order_item.save()
Try using the following instead, more complete:
def kitchen_view(request):
chef_view = OrderItem.objects.all()
if request.method == "POST":
food_status = request.POST.get("food_status")
order_item = OrderItem(food_status=food_status)
order_item.save()
return render(request, 'restaurants/kitchen_page.html', {'chef_view':chef_view})
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!
I have an interval type field that contains hours and minutes in this format: "28:00".
But in my template, it is translated to "1 day, 4:00:00"
How can I keep this "28:00" in my template?
My template:
<table class="table table-bordered ">
<thead align="center">
<th class="text-center" scope="col">User</th>
<th class="text-center" scope="col">Week number</th>
<th class="text-center" scope="col">Total H</th>
</thead>
<tbody>
{% for tp in resume_h %}
<tr scope="row">
<td class="text-center col-md-1">{{ tp.user_name }}</td>
<td class="text-center col-md-1">{{ tp.num_semaine }}</td>>
<td class="text-center col-md-1">{{ tp.hours_total|linebreaksbr }}</td>
</tr>
{% endfor %}
</tbody>
</table>
My model:
class hours(models.Model):
user_name = models.CharField(max_length=50, blank=True, null=True)
num_semaine = models.IntegerField(("No:"),blank=True, null=True)
hours_total = models.TimeField(("H"),blank=True, null=True)
def __str__(self):
return str(self.user_name)
Thank you