Django: template forloop multiple dictionaries - django

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

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)

Django loop in html issue

i had been trying to solve this problem for almost 3 hrs but i didnt get the result i want,
this is the result i want
this is my current result
this is my html
<table id="blacklistgrid" border="2px">
<tr>
<th>Students Name</th>
{% for student in teacherStudents %}<th >{{student.Date}}</th>{% endfor %}
<th data-id='headers' id='headerave'>Average</th>
</tr>
<tr>
<tbody id="scoreboard">
{% for students in studentname %}
<tr class="tr2">
<td><input type="text" name="students" value="{{student.id}}" id="student" hidden>{{students.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td>
<tr>
{% endfor %}
</tr>
<tr>
{% for studentss in Students %}
<td class="td" scope="row"><input type="text" name="students" value="{{student.id}}" id="student" hidden>{{studentss.Grade}}</td>{% endfor %}
<td data-id='row' id="ans"><input type='number' class='averages' step="any" name="average" readonly/></td>
</tr>
</tbody>
</table>
this is my views.py
teacherStudents = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade).distinct('Date')
studentname = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade).distinct('Students_Enrollment_Records')
Students = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade)
return render(request, 'Homepage/period.html',{"teacherStudents":teacherStudents,"Students":Students,"studentname":studentname})
my models.py
class studentsEnrolledSubjectsGrade(models.Model):
Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,
null=True,blank=True)
GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,
null=True,blank=True)
Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True)
Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+',
on_delete=models.CASCADE, null=True)
Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE,
null=True,blank=True)
grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE,
null=True,blank=True)
#Items = models.IntegerField(blank=True, null=True)
Date = models.DateField(null=True, blank=True)
Grade = models.FloatField(null=True, blank=True)
this is my data in admin.py
can you guys help me in my html loop? do you have suggestions? my database is postgresql
UPDATE just like mr #Chris said in the comment section, I want to create a table with a row per student and in the columns the grades at a specific date, Create the table in your view (e.g. as a list of lists or one annotated queryset) and use the template for rendering but i dont know how, please help me guys,
I would suggest generating the table in your view and the pass it to your template for rendering.
#views.py
def your_view(request):
students = StudentsEnrolledSubjectsGrade.objects.filter(put_in_your_filters).order_by('student_name', 'date').values('student_name', 'date', 'grade')
dates = list(students.values_list('date', flat=True).distinct().order_by('date'))
# table basics
table = []
student_name = None
table_row = None
columns = len(dates) + 1
# table header
table_header = ['Student Name']
table_header.extend(dates)
table.append(table_header)
for student in students:
if not student['student_name'] == student_name:
if not table_row is None:
table.append(table_row)
table_row = [None for d in range(columns)]
student_name = student['student_name']
table_row[0] = student_name
table_row[dates.index(student['date']) + 1] = student['grade']
table.append(table_row)
return render(request, 'my_template.html', {'table': table})
Then you can interate through all the rows of that table in you template:
<table id="blacklistgrid" border="2px">
<tr>
{% for v in table.0 %}
<td>{{ v }}</td>
{% endfor %}
</tr>
<tbody>
{% for row in table|slice:"1:" %}
<tr>
<td>{{ row.0 }}</td>
{% for c in row|slice:"1:" %}
<td>{{ c }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
You need to adapt that to your needs, it is just to give you an idea

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

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.

Display the descriptive status of options

I define a article_table model data in modles.py, especially set a options attribute for status
class Article(models.Model):
STATUS = (
(0, 'normal'),
(-1, 'deleted'),
)
block = models.ForeignKey(Block, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
content = models.CharField(max_length=1000) # set the widget
status = models.IntegerField(choices=STATUS)
date_created = models.DateTimeField(default=datetime.now)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
When I check the responded html, it display status with 0 from database rather than its description 'normal'
The status did not show normal as I intended.
The template of article_list.html
<table class="table table-bordered">
<tr>
<th>Status</th>
<th>Title</th>
<th>Author</th>
<th>Latest Updated</th>
</tr>
{% for article in articles %}
<tr>
<td>{{ article.status }}</td>
<td>{{ article.title }}</td>
<td>{{ article.author }}</td>
<td>{{ article.date_updated }}</td>
</tr>
{% endfor %}
</table>
How to solve such a problem?
If you use choices, then you can use get_<fieldname>_display() in the template, like this:
{{ article.get_status_display }}

django how to model this table correctly?

Following the suggestions from my last post I got this far:
Post model:
class Post(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
Group model:
class Group(models.Model):
title = models.CharField(max_length=200)
url = models.URLField(unique=True)
contact_updated = models.DateField(auto_now=False, auto_now_add=True)
group_status = models.CharField(max_length=20)
admin = models.CharField(max_length=20)
admin_status = models.CharField(max_length=20)
frequency = models.IntegerField() # allowed post frequency
frq_scale = models.CharField(max_length=20, blank=True)
obs = models.TextField(blank=True)
posts = models.ManyToManyField(Post, through='control.Control')
Control model:
class Control(models.Model):
published = models.DateField(auto_now=False, auto_now_add=False)
post = models.ForeignKey('posts.Post', on_delete=models.CASCADE)
group = models.ForeignKey('groups.Group', on_delete=models.CASCADE)
This is control for posts in groups. I can have 1 post published in many groups controlled from Control model.
CORRECTION:
It is possible for a Post to be published in many groups.
How can I produce the table (link above) with those models? Or perhaps there is something I need to change?
The table I want to produce
class Control(models.Model):
published = models.DateField(auto_now=False, auto_now_add=False)
post = models.ForeignKey('posts.Post', on_delete=models.CASCADE)
group = models.ForeignKey('groups.Group', on_delete=models.CASCADE)
class Meta:
unique_together = (post, group )
I ended up creating a dictionary in the view to be passed to the template.
I haven't changed the models.
This is the view:
def control_list(request):
group_status = STATUS_LIST
group_query_idx = 1
period_initial = date.today()-timedelta(days=30)
period_final = date.today()
if request.method == "POST":
filter_form = FilterControl(request.POST)
if filter_form.is_valid():
group_query_idx = int(filter_form.cleaned_data['group_status'])
period_initial = filter_form.cleaned_data['period_initial']
period_final = filter_form.cleaned_data['period_final']
else:
filter_form = FilterControl()
if group_query_idx:
filtered_groups = Group.objects.filter_by_status(group_status[group_query_idx])
queryset_list = Control.objects.filter_by_group_status(group_status[group_query_idx])\
.filter(published__range=[period_initial, period_final])
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(post__content__icontains=query) |
Q(post__title__icontains=query) |
Q(group__title__icontains=query) |
Q(group__admin__icontains=query) |
Q(group__obs__icontains=query)
).distinct() # avoid duplicated items
controls_per_group = {}
for group in filtered_groups:
control = queryset_list.filter(group_id=group.id)
controls_per_group[group.title] = control
context = {
"object_list": queryset,
"title": "Control",
"controls_per_group": controls_per_group,
"column": range(10),
"group_status": group_status,
"filter_form": filter_form,
}
return render(request, "control_list.html", context)
And this is the template:
<table class="table table-hover table-striped">
<thead class="thead-inverse">
<tr>
<th class="text-center">Action</th>
<th class="text-center">Group</th>
{% for value in column %}
<th class="text-center">#</th>
{% endfor %}
</tr>
</thead>
{% for key, value in controls_per_group.items %}
<tr>
<td class="text-center"><a class='btn btn-info btn-xs disabled' href="#"><i class="fa fa-pencil"></i></a>
<i class="fa fa-trash-o"></i></td>
<th class="text-center">{{ key }}</th>
{% for control in value %}
<th class="text-center">{{ control.published | date:"d/m/y" }}<br>{{ control.post.id }}</th>
{% endfor %}
</tr>
{% endfor %}