How do I bring through my data in Django Template view? - django

I'm trying to display my data from my HealthStats model to my template, however I can only pull through the user field. I've added the other fields to my template, but they're not showing. I would also like to be able to filter the output to only show records of the logged in user.
Models.py
class HealthStats(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now=True)
weight = models.DecimalField(max_digits=5, decimal_places=2)
run_distance = models.IntegerField(default=5)
run_time = models.TimeField()
class Meta:
db_table = 'health_stats'
ordering = ['-date']
def __str__(self):
return f"{self.user} | {self.date}"
Views.py:
class HealthHistory(generic.TemplateView):
model = HealthStats
template_name = 'health_hub_history.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['stats'] = HealthStats.objects.all()
return context
health_hub_history.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 text-center">
<h1>My Health History</h1>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<table class="table table-striped table-hover table-bordered">
<tr>
<td>User:</td>
<td>Weight (lbs):</td>
<td>Date:</td>
<td>Run Distance (km):</td>
<td>Run Time (HH:MM:SS):</td>
</tr>
{% for stat in stats %}
<tr>
<td>{{ user }}</td>
<td>{{ weight }} </td>
<td>{{ date }}</td>
<td>{{ run_distance }}</td>
<td>{{ run_time }}</td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock content %}
Any help would be appreciated!

In your template do this:
{% for stat in stats %}
<tr>
<td>{{stat.user}}</td>
<td>{{stat.weight}} </td>
<td>{{stat.date}}</td>
<td>{{stat.run_distance}}</td>
<td>{{stat.run_time}}</td>
</tr>
{% endfor %}
hope it will work

Related

how can you display data from three related tables in django?

I'm new to django and I'm having trouble displaying related data from three related databases in a table. I hope you can help me.
Models.py
class recursos (models.Model):
gruporecurso= models.CharField (max_length=50, choices=TIPORECURSO, default=TIPODEFAULT)
descripcion = models.CharField(max_length=100)
estado_disponible =models.BooleanField(default= True)
inventario = models.CharField(max_length=40,blank= True, null=True)
observacion = models.TextField(blank= True, null=True)
def __str__(self):
return self.descripcion
class remito (models.Model):
fecha = models.DateField()
hora = models.TimeField()
responsable = models. ForeignKey(personas, null=True, blank= True, verbose_name='Responsable',on_delete=models.CASCADE)
area_pedido = models.CharField(max_length=20, verbose_name='Área del pedido')
operador = models.CharField(max_length=40, choices=OPERADOR,verbose_name='Entregado por')
lugardeuso = models.CharField(max_length=40,verbose_name='Lugar uso')
observacion = models.TextField(blank= True, null=True)
class detalle_remito (models.Model):
id_remito = models.ForeignKey(remito, null=True, blank=False, on_delete=models.CASCADE)
id_recurso = models.ForeignKey(recursos, null=True, blank=False, on_delete=models.CASCADE)
cantidad = models.IntegerField(default=1)
def __str__(self):
return f' {self.id_recurso.descripcion}'
Views.py
def home (request):
remitos= remito.objects.all()
recursolist= detalle_remito.objects.all()
page= request.GET.get('page',1)
try:
paginator = Paginator(remitos,5)
remitos=paginator.page(page)
except:
raise Http404
return render(request,"RemitoTicapp/home.html",{'entity': remitos ,'recursolist':recursolist,'paginator': paginator})
home.html
{% extends "RemitoTicapp/base.html" %}
{% load static %}
{% block content %}
<!-- Heading
<section class="page-section clearfix">
<div class="container">
</div>
</div>
</section>
-->
<!-- Message -->
<section class="page-section cta">
<div class="container mx-auto">
<div class="row">
<!--<div class="col-xl-9 mx-auto"> -->
<div class="cta-inner text-center rounded">
<h2 class="section-heading mb-2">
<span class="section-heading-upper">Sistema de Gestión de pedidos</span>
<span class="section-heading-lower"> Elementos cedidos</span>
</h2>
<!--<p class="mb-0"> -->
<table class="table table-striped" bg white>
<thead>
<tr>
<th scope="col">Fecha entrega</th>
<th scope="col">Responsable</th>
<th scope="col">Area Pedido</th>
<th scope="col">Lugar de uso</th>
<th scope="col">Recurso / cantidad</th>
<th scope="col">Operador</th>
<th scope="col">Observaciones</th>
</tr>
</thead>
<tbody>
{% for remito in entity %}
<tr>
<td scope="row">{{ remito.fecha }}</td>
<td>{{ remito.responsable }}</td>
<td>{{ remito.area_pedido }}</td>
<td>{{ remito.lugardeuso }}</td>
<td> {% for recurso in recursolis %}
{% if recurso.id_remito == remito.pk %}
<li>{{ recurso.id_recurso.descripcion }} {{recurso.cantidad}}</li>
{% endif %}
{% endfor %}
</td>
<td>{{ remito.operador }}</td>
<td>{{ remito.observacion }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div>
{% include 'RemitoTicapp/paginator.html' %}
</div>
<!-- </p> -->
</div>
</div>
<!-- </div> -->
</div>
</section>
{% endblock%}
We should show the data of Remito with the resources of detalle_remito with the description of each one of them from the recursos table.
From already thank you very much
Django will make the reverse foreign key relation accessible with the related model's name followed by a _set-suffix, exposing an instance of RelatedManager.
{% for detalle_remito in remito.detalle_remito_set.all %}
{{ detalle_remito.id_recurso.descripcion }}
{% endfor %}
No need to gather addional data for that in your view.
Where you have {% for recurso in recursolis %}, you could instead write {% for recurso in remito.detalle_remito_set.all %} and remove the if statement - it will loop through the detalle_remito objects that are connected to the recurso object

How can i display count of each column in django

Display
I would like to count the number of students for each subjects but currently it only displays the number of students for one subject. it only counts the number of student for one subject but i would like to count the number of students in each subject
Added the models.py. Ps still new to django
views.py
class SubjectView(TemplateView):
template_name='subjects.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
username=self.request.user.id
#filter subject taught by lecturer
classdets=ClassDetail.objects.all().filter(teacher=username).values_list('subject_id')
print(classdets)
#filters all subjects from the class details
subj=Subject.objects.filter(id__in=classdets)
print(subj)
#counts number of students
subjID=Subject.objects.values('id')
num_student=ClassDetail.objects.filter(id__in=subjID).count
print(num_student)
context['subjects'] = subj
context['no_students'] = num_student
return context
template
{% extends "base.html" %}
{% load static %}
{% block title %}Subjects{% endblock title %}
{% block sidenavbar %}
{% include 'partials/sidenavbar.html' %}
{% endblock %}
{% block navbar %}
{% include 'partials/navbar.html' %}
{% endblock %}
{% block subject %}
<div class="container-fluid">
<div class="col">
<div class="card bg-transparent">
<!-- Card header -->
<div>
<div class="card-header bg-transparent border-0">
<h3 class="mb-0" style="text-transform: uppercase">Current Subjects</h3>
{% comment %} View Students {% endcomment %}
</div>
</div>
<!-- Translucent table -->
<div class="table-responsive">
<table class="table align-items-center table-flush" id="datatable-buttons">
<thead class="thead-light">
<tr>
<th>Subject Name</th>
<th>Subject Code</th>
<th>Number of Students</th>
{% comment %} <th>Generate Attendance Code</th> {% endcomment %}
</tr>
</thead>
{% if user.is_authenticated %}
{% for subject in subjects %}
<tbody class="list" style="text-transform: capitalize">
<tr>
<th scope="row">
<div class="media align-items-center">
<a href="#" class="avatar rounded-circle mr-3">
{% if subject.thumbnail %}
<img alt="Logo" src="{{subject.thumbnail.url}}" />
{% endif %}
</a>
<div class="media-body">
<span class="name mb-0 text-sm">{{subject}}</span>
</div>
</div>
</th>
<td class="budget">{{subject.code}}</td>
<td>
<div class="d-flex align-items-center">
<span class="completion mr-2">{{no_students}}</span>
</div>
</td>
<td>
{% comment %}
<div class="d-flex align-items-center">
<span class="completion mr-2">{{attendace_code}}</span>
</div>
{% endcomment %}
</td>
</tr>
</tbody>
{% endfor %}
{% endif %}
</table>
</div>
</div>
</div>
</div>
{% endblock %}
models
def get_thumbnail(instance, filename):
path = f"static/assets/img/custom/{filename}"
return path
class Subject(models.Model):
code=models.CharField(max_length=8,unique=True,default="")
name=models.CharField(max_length=100,unique=True)
thumbnail=models.ImageField(blank=True,null=True,upload_to=get_thumbnail)
def __str__(self):
return f'{self.name}'
class Meta:
unique_together = ('name', 'code')
class ClassDetail(models.Model):
teacher=models.ForeignKey(UserProfile,on_delete=models.PROTECT)
subject=models.ForeignKey(Subject, on_delete=models.PROTECT, default="")
student=models.ManyToManyField(UserProfile,related_name="student")
def __str__(self):
return f'{self.subject}'
class Meta:
unique_together = ('teacher', 'subject')
userprofile
class UserProfile(AbstractUser):
ROLE_LECTURER = 'lecturer'
ROLE_STUDENT = 'student'
ROLE_ADMIN = 'admin'
ROLE_CHOICES = (
(ROLE_LECTURER, _('Lecturer')),
(ROLE_STUDENT, _('Student')),
(ROLE_ADMIN, _('Admin')),
)
STATUS_ACTIVE = 'active'
STATUS_INACTIVE = 'inactive'
STATUS_SUSPENDED = 'suspended'
STATUS_EXPIRED = 'expired'
STATUS_CHOICES = (
(STATUS_ACTIVE, _('Active')),
(STATUS_INACTIVE, _('Inactive')),
(STATUS_SUSPENDED, _('Suspended')),
(STATUS_EXPIRED, _("Expired")),
)
username = models.CharField(max_length=11, unique=True, verbose_name="Relevant ID")
status = models.CharField(_('status'), max_length=50, choices=STATUS_CHOICES, default=STATUS_ACTIVE)
role = models.CharField(_('role'), max_length=50, choices=ROLE_CHOICES, default="")
def __str__(self):
return f'{self.username} ({self.first_name})'
USERNAME_FIELD = 'username'
num_student =subjID.classdetail_set.all().count()
print(num_student)

Custom format an inline formset

I'm create a template in Django, adding a form and formset to the template, but I don't like how it's formatting the formset by default. I've tried .as_table and .as_ul, but it's not formatting it to my liking. I'd like to see the following from the formset:
Ingredient Percentage Delete
ingredient1 .55
ingredient2 .22
ingredient3 .33
I've tried the code in "https://stackoverflow.com/questions/17492374/how-to-render-formset-in-template-django-and-create-vertical-table" but when I implement it, I'm getting two extra column, "ID" and "Recipe Name". I don't know where those columns are coming from and I don't know how to get rid of them.
Example:
models.py
class Recipe(models.Model):
name = models.CharField(max_length=200, null=True)
description = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.name
class Recipe_Ingredient(models.Model):
recipe_name = models.ForeignKey(Recipe, null=True, on_delete = models.SET_NULL)
ingredient = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL)
recipe_percent = models.DecimalField(max_digits=8, decimal_places=5, blank=True)
views.py
def recipeUpdate(request, recipe_id):
RecipeIngredientFormSet2 = inlineformset_factory(Recipe, Recipe_Ingredient, extra=10, fields=('ingredient', 'recipe_percent'))
recipe = Recipe.objects.get(pk=recipe_id)
formset = RecipeIngredientFormSet2(instance=recipe)
context = {'formset' : formset}
return render(request, 'accounts/recipe_form.html', context)
recipe_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{{ form }}
<p></p>
<!--{{ formset.as_table }}-->
<p></p>
{{ formset.management_form}}
<!--{% for form in formset %}
{{ form }}
{% endfor %}-->
<table>
<thead>
{% for form in formset %}
{% if forloop.first %}
{% for field in form %}
<th>{{ field.label_tag }}</th>
{% endfor %}
{% endif %}
</thead>
<tbody>
<tr>
{% for field in form %}
<td>{{ field }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
<input type="submit" name="Submit">
</form>
</div>
</div>
</div>
{% endblock %}
Found the answer. You've got to add the formset with a .management_form tag, then in table, loop through each form in form set. If it's the first loop, add the headers to the tables. In all other loops, add each field from the form that you want in the table.
The updated HTML that I'm using is below.
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{ form }}
{{ formset.management_form }}
<table>
{{ form.id }}
{% for p in formset %}
<tr>
{% if forloop.first %}
<td>{{ p.DELETE.label_tag }}</td>
<td>{{ p.ingredient.label_tag }}</td>
<td>{{ p.recipe_percent.label_tag }}</td>
<p></p>
{% endif %}
</tr>
<!--{{ p.id }}
{{ p.ORDER }}-->
<tr></tr>
<td>{{ p.DELETE }}</td>
<td>{{ p.ingredient }}</td>
<td>{{ p.recipe_percent }}</td>
</tr>
{% endfor %}
</table>
<input type="submit" name="Submit">
</form>
</div>
</div>
</div>
{% endblock %}

Cant write correct queryset in Django

i have three models:subplan,subplanfeature and price.I wanna show gym price table,but it shows wrong result
class SubPlan(models.Model):
title = models.CharField(max_length=150)
def __str__(self):
return self.title
class SubPlanFeature(models.Model):
title = models.CharField(max_length=150)
def __str__(self):
return self.title
class Price(models.Model):
gym=models.ForeignKey(Gym,on_delete=CASCADE)
subplan=models.ForeignKey(SubPlan,on_delete=CASCADE,related_name='subplans')
feature=models.ForeignKey('SubPlanFeature',on_delete=CASCADE,related_name='features')
price = models.IntegerField()
highlight_status = models.BooleanField(default=False,null=True)
here is my view
def pricing(request,slug):
gym=models.Gym.objects.get(slug=slug)
price=models.Price.objects.all()
banners=models.Banners.objects.filter(gym=gym)
plans1= models.Price.objects.filter(gender='man',gym=gym)
dfeatures1=models.Price.objects.filter(gender='man',gym=gym)
return render(request, 'pricing.html',{'plans1':plans1,'dfeatures1':dfeatures1,'gym':gym})
and template here
<thead>
<tr>
<th style="width: 34%;"></th>
{% for plan in plans1 %}
<th style="width: 22%;">{{plan.subplan}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for feature in dfeatures1 %}
<tr>
<th scope="row" class="text-start">{{feature.feature}}</th>
{% for plan in plans1 %}
<td>
{{plan.price}} Azn.
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
it should display as this
enter image description here
but shows this
enter image description here
what should i change?
you can use "forloop" counter in template
...
{% for feature in dfeatures1 %}
<tr>
<th scope="row" class="text-start">{{feature.feature}}</th>
{% for plan in plans1 %}
<td>
# only print when counter in parent loop are the same
{% if forloop.parentloop.counter == forloop.counter %}
{{plan.price}} Azn.
{% endif %}
</td>
{% endfor %}
</tr>
{% endfor %}

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.