How to use an atribbute of an object Many To Many? - django

I'm using Django 2.1
I've got these 2 models with a ManyToMany relationship:
class Ingrediente(models.Model):
produtor = models.ForeignKey('auth.User', on_delete=models.CASCADE, default=10)
nome = models.CharField(max_length=200)
descricao = models.TextField()
quantidade = models.DecimalField(max_digits=10, decimal_places=3)
custo = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return self.nome
e
class Produto(models.Model):
nome = models.CharField(max_length=200)
descricao = models.TextField()
ingredientes = models.ManyToManyField(Ingrediente)
utilitarios = models.ManyToManyField(OutrosCustos)
def __str__(self):
return self.nome
I use the this view to return a list with all objects of Class Produto:
def produtos_list(request):
produtos = Produto.objects.filter()
return render(request, 'egg_app/produtos_list.html', {'produtos':produtos})
And in my template I write this:
<table class="table">
<thead>
<tr>
<th scope="col">Nº Produto</th>
<th scope="col">Nome</th>
<th scope="col">Ingredientes</th>
<th scope="col">Custo</th>
</tr>
</thead>
<tbody>
{% for p in produtos %}
<tr>
<th scope="row">{{ p.pk }}</th>
<td>{{ p.nome }}</td>
<td>{{ p.ingredientes }}</td>
<td>custo teste</td>
</tr>
{% endfor %}
</tbody>
</table>
But my result in the column Ingredientes has been egg_app.Ingrediente.None and not the name of the Ingrediente of the relationship (between Ingrediente and Produto). In my Django admin page, I associate this, so I'm sure about the relationship.

Related

raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'generate_payroll' with no arguments not found

this is my views.py
def qualified(request, employee_id):
current_date = datetime.date.today()
_history = PayrollModel.objects.all()
for her in _history:
if(her.employee_id_id == employee_id):
# mnt = her
if((current_date.month != her.month_year.month
and current_date.month > her.month_year.month)
and current_date.year == her.month_year.year):
return messages.success(request, "HAPPY BD")
else:
return messages.success(request, "SAD BD")
def generate_payroll(request, employee_id):
qualification = qualified(request, employee_id=employee_id)
current_date = datetime.date.today()
if (qualification == True):
overTimeValue = calculate_overtime(employee_id)
allowanceValue = calculate_allowance(employee_id)
bonusValue = calculate_bonus(employee_id)
employee = EmployeeModel.objects.get(pk=employee_id)
salary = PayGradeModel.objects.get(pk=employee.basic_salary_id)
ssf = calculate_ssf(salary)
netValue = (float(salary.amount) + float(overTimeValue) +
float(bonusValue) + float(allowanceValue)) - float(ssf) # allowanceValue
payroll = PayrollModel.objects.create(employee_id_id=employee_id)
payroll.month_year = current_date
payroll.basicSalary = salary.amount
payroll.ssf_deduction = float(ssf)
payroll.over_time = float(overTimeValue)
payroll.bonus = float(bonusValue)
payroll.allowance = allowanceValue
payroll.gross_pay = salary.amount
payroll.net_salary = float(netValue)
payroll.save()
messages.success(request, 'payroll generated successfully')
return HttpResponseRedirect('/get_payroll')
else:
# payrolls = PayrollModel.objects.filter(employee_id_id=employee_id)
return render(request, 'payrolls/get_payroll.html', {'payrolls': payroll}
models.py
class PayrollModel(models.Model):
month_year = models.DateField(null=True)
# month_year = MonthField(
# "Month value", help_text="some help...", null=True)
gross_pay = models.CharField(max_length=100, null=True)
bonus = models.CharField(max_length=100, null=True)
allowance = models.CharField(max_length=100, null=True)
ssf_deduction = models.CharField(max_length=100, null=True)
over_time = models.CharField(max_length=100, null=True)
net_salary = models.CharField(max_length=100, null=True)
employee_id = models.ForeignKey(
EmployeeModel, on_delete=models.CASCADE, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
updated = models.DateTimeField(auto_now=True, null=True)
class Meta:
db_table = 'payrolls'
ordering = ['-updated', '-date_created']
urls.py
path('employees/<int:pk>/payrolls/generate_payroll',
views.generate_payroll, name='generate_payroll'),
get_payroll.html
<h4>Payroll for {{ payrolls.first.employee_id.first_name}} {{ payrolls.first.employee_id.last_name }}</h4>
<table class="table">
<thead>
<tr>
<th scope="col">Payroll Month</th>
<th scope="col">Gross Pay</th>
<th scope="col">Allowances</th>
<th scope="col">Bonus</th>
<th scope="col">Overtime</th>
<th scope="col">Social Security</th>
<th scope="col">Net salary</th>
<th scope="col">Payslip</th>
</tr>
</thead>
<tbody>
{% for payroll in payrolls %}
<tr>
<td>{{ payroll.month_year }}</td>
<td>{{ payroll.gross_pay }}</td>
<td>{{ payroll.allowance }}</td>
<td>{{ payroll.bonus }}</td>
<td>{{ payroll.over_time }}</td>
<td>{{ payroll.ssf_deduction }}</td>
<td>{{ payroll.net_salary }}</td>
<td>Get payslip</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
what I want to archive is when a user clicks the generate payroll button the **generate_payroll function should be excited and save the result to the db. in the button on my templates I pass this url but I keep getting the error django.urls.exceptions.NoReverseMatch: Reverse for 'generate_payroll' with no arguments not found. 1 pattern(s) tried: ['employees/(?P[0-9]+)/payrolls/generate_payroll\Z']
You need to add a parameter for the URL's.
Refer https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#url
In template try this
<td>
Get payslip
</td>
In your view add this
from django.core.urlresolvers import reverse
payroll.save()
messages.success(request, 'payroll generated successfully')
url = reverse('generate_payroll', kwargs={'pk': employees.id})
return HttpResponseRedirect(URL)

Why doesn't Django template show data correctly?

I'm a new Django programmer and I'm writing a learning app. This app have a foreign key relations and I use prefetch_related method. This system runs well ;-)
My problem is at the template, when I show the data from the table, the browser shows this menssages:
ID Bill number Warehouse Article Quantity Price (<<-- columns)
1 CabeceraDeFacturas object (1) Primer almacén Bolsa plástico .05 mm. KK. 10 1
...
The questions are:
¿Why does show the message "CabeceraDeFacturas object (1)" instead of a bill number?
¿Can I fix this? ¿How?
The information about is:
Part of models.py
class CabeceraDeFacturas(models.Model):
ID_cliente = models.ForeignKey('Clientes',on_delete=models.CASCADE)
fecha_factura = models.DateField('Fecha de factura: ')
ID_formaDePago = models.ForeignKey('FormasDePago',on_delete=models.CASCADE)
Porcentaje_IVA = models.PositiveSmallIntegerField(default=21)
Total_factura = models.IntegerField()
class Meta:
ordering = ('id',)
#def __str__(self):
# return self.id
class LineasDeFacturacion(models.Model):
ID_factura = models.ForeignKey('CabeceraDeFacturas',on_delete=models.CASCADE)
ID_almacen = models.ForeignKey('Almacen',on_delete=models.CASCADE)
ID_articulo = models.ForeignKey('Articulos',on_delete=models.CASCADE)
cantidad = models.IntegerField(default=1)
Precio = models.IntegerField()
class Meta:
default_related_name = 'lineas'
# def __str__(self):
# return str(self.ID_factura)
Part of views.py
class VerFacturaCompleta(ListView):
#model = CabeceraDeFacturas
model = LineasDeFacturacion
template_name = "ListarTodasLasFacturasConLineas.html"
# recuperar las facturas completas y líneas --> comprobar
# queryset = CabeceraDeFacturas.objects.all().select_related('lineas')
queryset = LineasDeFacturacion.objects.all().prefetch_related('ID_factura')
paginate_by = 10
And finally, the template:
<h1>Listar facturas</h1>
<table class="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Factura</th>
<th scope ="col">Almacén</th>
<th scope ="col">Artículo</th>
<th scope ="col">Cantidad</th>
<th scope="col">Precio</th>
<!--<th scope="col">Almacén</th>-->
</tr>
</thead>
<tbody>
{% for articulo in object_list %}
<tr>
<!--<th scope="row">{{ articulo.pk }}</th>-->
<th scope ="row"> {{ articulo.pk }} </th>
<td>{{ articulo.ID_factura }}</td>
<td>{{ articulo.ID_almacen }}</td>
<td>{{ articulo.ID_articulo }}</td>
<td>{{ articulo.cantidad }}</td>
<td>{{ articulo.Precio }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<hr>
Thanks a lot!
Well, the template only uses "object_list". This object_list comes form a instruction like this "queryset = LineasDeFacturacion.objects.all().prefetch_related('ID_factura')"; which is in a view.
The view which I use for this template is the next:
class VerFacturaCompleta(ListView):
#model = CabeceraDeFacturas
model = LineasDeFacturacion
template_name = "ListarTodasLasFacturasConLineas.html"
# recuperar las facturas completas y líneas --> comprobar
# queryset = CabeceraDeFacturas.objects.all().select_related('lineas')
queryset = LineasDeFacturacion.objects.all().prefetch_related('ID_factura')
paginate_by = 10
I don't use a context inside the view, only, the view pass an object_list (queryset) to the template.
Thanks for your time!
I found the mistake. The problem was in the models.py declaration. The CabeceraDeFactura class didn't had a data return. When I fixed this mistake
def __str__(self):
return str(self.id)
the template shows the data correctly.
Thanks for your time!

How to set field value based on what user click in Django ListView

I have two models Parent and Child. I would like to display both values in a ListView, whereby there is an Add Child button for each family.
Supposed that the parents are already populated, when I click Add Child, I would love that in the form of Child, the parent field are already set to the corresponding family name (please see code below).
Simple model would be:
class Family(models.Model):
family_name = models.CharField(max_length=100, default='', blank=False)
father_name = models.CharField(max_length=100, blank=False, default='')
mother_name = models.CharField(max_length=100, blank=False, default='')
def get_absolute_url(self):
return reverse('family-list')
def __str__(self):
return str(self.family_name)
class Children(models.Model):
parent = models.ForeignKey(Family, blank=False, default=None, null=True, on_delete=models.PROTECT, related_name='their_child')
child_name = models.CharField('4Jet ID', max_length=100, default='', blank=False)
birth_date = models.DateField(default=timezone.now, blank=False)
def get_absolute_url(self):
return reverse('family-list') # both return to family list view
The View using simple generic view:
class FamilyList(ListView):
model = Family
template_name = '/family_list.html'
context_object_name = 'fam_list'
# class NewParent omitted
class NewChild(CreateView):
model = Children
template_name = '/child_new.html'
context_object_name = 'child'
fields = [
'parent', 'child_name', 'birth_date'
]
and the simplified template:
<!--file: family_list.html-->
{% for fam in fam_list %}
<table>
<tr>
<th class="header"></th>
<th class="header">Family Name</th>
<th class="header">Father's First Name</th>
<th class="header">Mother's First Name</th>
<th class="header">Add Child</th>
</tr>
<tr>
<td>+</td>
<td>{{ fam.family_name }}</td>
<td>{{ fam.father_name }}</td>
<td>{{ fam.versand_datum | date:"d M, Y" }}</td>
<td>Add Child
</td>
</tr>
<tr >
<td colspan="5">
<div>
<table>
<tr>
<th class="header">Child's First Name</th>
<th class="header">Date of Birth</th>
</tr>
{% for child in fam.their_child.all %}
<tr>
<td>{{ child.child_name }}</td>
<td>{{ child.birth_date | date:"d M, Y" }}</td>
</tr>
{% endfor %}
</table>
</div>
</td>
</tr>
</table>
{% endfor %}
I've tried playing with the get_initial method in the NewChild view but by setting pdb trace within the method, the self.request.GET.getlist() gives me empty list.
Again, I just want that when I click the Add Child button in the template, the parent field in the child form will be set corresponding to the parent that I clicked.
Any idea how to do that?
All help are much appreciated
Your template is only a template to wiew a result, not to record an other one.
You must write a form and the most simple to you is to follow the initial Django tutorial.
Url : https://docs.djangoproject.com/en/2.1/intro/tutorial04/
You need :
- write a form template
- write a service to record you form result.
- and write a new template to view your record.
Take the time to do the initial tutorial, it is simple to follow

Right number of rows, but they're empty

I'm trying to display some tables, but they come up empty. The part that gets me is the number of rows is correct, but they are completely blank. If the table has 9 entries, I get 9 empty rows.
The same code is working for a different table
tables.py:
class VouchersTable(tables.Table):
class meta:
model = Vouchers
fields = ('event_name', 'pk', 'valid_start', 'valid_end', 'lab_duration', 'user_email', 'redeem_date' )
views.py:
class ReportsView(LoginRequiredMixin, TemplateView):
template_name = 'reports.html'
def get_context_data(self, **kwargs):
context = super(ReportsView, self).get_context_data(**kwargs)
vouchers = VouchersTable(Vouchers.objects.all())
RequestConfig(self.request, paginate=False).configure(vouchers)
context['vouchers'] = vouchers
return context
reports.html:
{% extends "base.html" %}
{% load render_table from django_tables2 %}
{% block content %}
{% render_table vouchers %}
{% endblock content %}
models.py:
class Vouchers(models.Model):
creator_uid = models.IntegerField()
user_id = models.IntegerField()
username = models.CharField(max_length=255)
user_email = models.CharField(max_length=100)
event_name = models.CharField(max_length=255)
event_code = models.IntegerField()
valid_start = models.IntegerField()
valid_end = models.IntegerField()
redeemed = models.IntegerField()
redeem_date = models.IntegerField()
lab_version = models.CharField(max_length=40)
lab_model = models.IntegerField()
lab_id = models.IntegerField()
lab_duration = models.IntegerField()
resulting html (empty lines removed):
<div class="table-container">
<table>
<thead>
<tr>
</tr>
</thead>
<tbody>
<tr class="even">
</tr>
<tr class="odd">
</tr>
<tr class="even">
</tr>
<tr class="odd">
</tr>
<tr class="even">
</tr>
<tr class="odd">
</tr>
<tr class="even">
</tr>
<tr class="odd">
</tr>
<tr class="even">
</tr>
</tbody>
</table>
</div>
Oh well...
You've declared the table like this:
class VouchersTable(tables.Table):
class meta:
model = Vouchers
fields = ('event_name', 'pk', 'valid_start', 'valid_end', 'lab_duration', 'user_email', 'redeem_date' )
The correct way to write it is class Meta (Meta with a capital M): https://github.com/jieter/django-tables2

Django: template forloop multiple dictionaries

I need to load the the price of a liquor associated with the store, along wit the other data in the general liquor database. I know how to load the data in, and how to display in the info in two different tables, but I need that store price to simply be another row in the existing table, and I'm not sure how to do that. Here is the view:
def store(request, store_id=1):
a = Store.objects.get(StoreID=store_id)
b = StoreLiquor.objects.filter(storeID__exact=a).values_list('liquorID', flat=True)
x = StoreLiquor.objects.filter(storeID_exact=a)
args = {}
args['liquors'] = Liquor.objects.filter(id__in=b)
args['prices'] = x
args['a'] = a
return render(request, 'store.html', args)
Here is the html:
<pre>
<code>
{% if liquors.count > 0 %}
<table class="sortable">
<thead>
<tr>
<th scope="col">Liquor Code</th>
<th scope="col">Brand Name</th>
<th scope="col">Vendor Name</th>
</tr>
</thead>
<tbody>
{% for liquor in liquors %}
<tr>
<td>{{ liquor.LiquorCode }}</td>
<td>{{ liquor.BrandName }}</td>
<td>{{ liquor.VendorName }}</td>
<td>{{ liquor.StorePrice }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>None to show!</p>
{% endif %}
</code>
</pre>
Models:
class StoreLiquor(models.Model):
StoreLiquorID = models.AutoField(primary_key=True)
liquorID = models.ForeignKey(Liquor)
storeID = models.ForeignKey(Store)
StorePrice = models.DecimalField('Store Price', max_digits=5, decimal_places=2)
class Liquor(models.Model):
LiquorCode = models.PositiveSmallIntegerField('Liquor Code', max_length=5)
BrandName = models.CharField('Brand Name', max_length=32)
ADANumber = models.PositiveSmallIntegerField('ADA Number', max_length=3)
ADAName = models.CharField('ADA Name', max_length=25)
VendorName = models.CharField('Vendor Name', max_length=25)
LiquorType = models.CharField('ADA Name', max_length=20)
Proof = models.DecimalField(max_digits=3, decimal_places=1)
BottleSize = models.CharField('Bottle Size', max_length=7)
PackSize = models.PositiveSmallIntegerField('PackSize', max_length=3)
OnPremisePrice = models.DecimalField('On Premise Price', max_digits=5, decimal_places=2)
OffPremisePrice = models.DecimalField('Off Premise Price', max_digits=5, decimal_places=2)
ShelfPrice = models.DecimalField('Shelf Price', max_digits=5, decimal_places=2)
GlobalTradeItemNumber1 = models.BigIntegerField('Global Trade Item Number 1', max_length=14)
GlobalTradeItemNumber2 = models.BigIntegerField('Global Trade Item Number 2', max_length=14)
class Store(models.Model):
StoreID = models.AutoField(primary_key=True)
How about something like this:
View:
def store(request, store_id=1):
store = Store.objects.get(StoreID=store_id)
args = {}
args['store'] = store
return render(request, 'store.html', args)
Template:
<pre>
<code>
{% if store.storeliquor_set.count %}
<table class="sortable">
<thead>
<tr>
<th scope="col">Liquor Code</th>
<th scope="col">Brand Name</th>
<th scope="col">Vendor Name</th>
</tr>
</thead>
<tbody>
{% for storeliquor in store.storeliquor_set.all %}
<tr>
<td>{{ storeliquor.liquorID.LiquorCode }}</td>
<td>{{ liquor.liquorID.BrandName }}</td>
<td>{{ storeliquor.liquorID.VendorName }}</td>
<td>{{ storeliquor.StorePrice }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>None to show!</p>
{% endif %}
</code>
</pre>
Although I would recommend you to change your model to something like this (according to the python style guide):
class StoreLiquor(models.Model):
liquor = models.ForeignKey(Liquor)
store = models.ForeignKey(Store)
price = models.DecimalField('Store Price', max_digits=5, decimal_places=2)
class Liquor(models.Model):
liquor_code = models._positiveSmallIntegerField('Liquor Code', max_length =5)
brand_name = models.CharField('Brand Name', max_length =32)
ada_number = models._positiveSmallIntegerField('ADA Number', max_length =3)
ada_name = models.CharField('ADA Name', max_length =25)
vendor_name = models.CharField('Vendor Name', max_length =25)
liquor_type = models.CharField('ADA Name', max_length =20)
proof = models.DecimalField(max_digits =3, decimal_places =1)
bottle_size = models.CharField('Bottle Size', max_length =7)
pack_size = models._positiveSmallIntegerField('PackSize', max_length =3)
on_premise_price = models.DecimalField('On Premise Price', max_digits =5, decimal_places =2)
off_premise_price = models.DecimalField('Off Premise Price', max_digits =5, decimal_places =2)
shelf_price = models.DecimalField('Shelf Price', max_digits =5, decimal_places =2)
global_trade_item_number_1 = models.BigIntegerField('Global Trade Item Number 1', max_length =14)
global_trade_item_number_2 = models.BigIntegerField('Global Trade Item Number 2', max_length =14)
class Store(models.Model):
pass