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
Related
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
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)
I keep getting this error everytime I try to access the class assignment page.
Below is the code of my project.
Models.py
class logger(AbstractUser):
is_student = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
class Student(models.Model):
username = models.OneToOneField(logger,on_delete=models.CASCADE,primary_key=True,related_name='Student')
name=models.CharField(max_length=250)
roll_no = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
def __str__(self):
return self.name
class Meta:
ordering = ['roll_no']
class Teacher(models.Model):
username = models.OneToOneField(logger,on_delete=models.CASCADE,primary_key=True,related_name='Teacher')
name = models.CharField(max_length=250)
subject_name = models.CharField(max_length=250)
email = models.EmailField(max_length=254)
class_students = models.ManyToManyField(Student,through="StudentsInClass")
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('teacher_detail',kwargs={'pk':self.pk})
Views.py
#login_required
def class_assignment(request):
student = request.user.Student
assignment = SubmitAssignment.objects.filter(student=student)
assignment_list = [x.submitted_assignment for x in assignment]
return render(request,'class_assignment.html',{'student':student,'assignment_list':assignment_list})
class_assignment.html
{% extends 'base.html' %}
{% block content %}
<div class="container">
<div class="jumbotron">
{% if student.student_assignment.count == 0 %}
<h2>No assignments Yet</h2>
{% else %}
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Assignment Name</th>
<th scope="col">Uploaded By</th>
<th scope="col">Uploaded Date</th>
<th scope="col">Download</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
{% for assignment in student.student_assignment.all %}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td>{{ assignment.assignment_name }}</td>
<td>{{ assignment.teacher }}</td>
<td>{{ assignment.created_at }}</td>
<td>Download</td>
{% if assignment in assignment_list %}
<td>Submitted</td>
{% else %}
<td>Submit</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
</div>
</div>
{% endblock %}
Can anyone please help me and tell me if something is wrong in the code or not, I have tried almost everything including syncing the database, trying to migrate the project, deleting and re-creating the database.
Any help would be appreciated, Thank you and if you need anything else please comment and I'll upload it.
I'm working on a project on django, I'm using the built in view ArchiveListView, and I want to sort records to be grouped by a common attribute.
So django ORM don't have a group by query, so I tried to do this on the template using regroup tag, but I think it take a long time and it doesn't give me the grouped record as I want
this is the models I have :
class Vehicle(models.Model):
serie = models.CharField(max_length=18, unique=True, blank=True, null=True)
matricule = models.CharField(max_length=18, unique=True, blank=True, null=True)
ww = models.CharField(max_length=18,blank=True, null=True)
marque_id = models.ForeignKey('Marque', blank=True, null=True, on_delete=models.SET_NULL)
entry_into_service = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True)
mouchard = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True)
extinguisher = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True, help_text="extincteur expiratiOn date")
city_id = models.ForeignKey('City', blank=True, null=True, on_delete=models.SET_NULL)
region_id = models.ForeignKey('Region', blank=True, null=True, on_delete=models.SET_NULL)
driver_id = models.ForeignKey('Driver', blank=True, null=True, on_delete=models.SET_NULL)
class Meta:
ordering = ['serie','matricule']
def __str__(self):
return (self.matricule)
class GazStation(models.Model):
name = models.CharField(max_length=128, blank=True)
city_id = models.ForeignKey('City', blank=True, null=True, on_delete=models.SET_NULL)
geo_localization = gis_models.PointField(blank=True, null=True)
class Meta:
ordering = ['city_id','name']
def __str__(self):
return '%s %s' % (self.name, self.city_id.city)
class Refuel(models.Model):
vehicle_id = models.ForeignKey('Vehicle', blank=True, null=True, on_delete=models.SET_NULL)
driver_id = models.ForeignKey('Driver', blank=True, null=True, on_delete=models.SET_NULL, limit_choices_to ={'is_driver':True})
Controlor_id = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='controlor_refuel', on_delete=models.SET_NULL, limit_choices_to ={'is_controlor':True})
gaz_station_id = models.ForeignKey('GazStation', blank=True, null=True, on_delete=models.SET_NULL)
date_time_creation = models.DateTimeField(auto_now=False, auto_now_add=True)
date_time_modified = models.DateTimeField(auto_now=True, blank=True)
odometer_reading = models.PositiveIntegerField(blank=True)
fuel_quantity = models.DecimalField(max_digits=5, decimal_places=2)
fuel_unit_price = models.DecimalField(max_digits=6, decimal_places=2)
class Meta:
ordering = ['gaz_station_id','-date_time_creation']
def __str__(self):
return (self.vehicle_id.serie)
and this is the class view I'm using:
####### refuel view filtred by year #################
class RefuelsListViewSup(LoginRequiredMixin, YearArchiveView):
queryset = Refuel.objects.order_by('vehicle_id').all()
date_field = "date_time_creation"
make_object_list = True
allow_future = True
and the template to display this view is:
{% extends 'base.html' %}
{% load mathfilters %}
{% block title %}
<title>Refuels Archive</title>
{% endblock title %}
{% block content %}
<div class="container">
<h1>La liste des gazoile archivé </h1>
<ul>
{% for date in date_list %}
<li>{{ date|date }}</li>
{% endfor %}
</ul>
<div>
<h1>All Refuels for {{ year|date:"Y" }}</h1>
{% regroup object_list by vehicle_id as vehicle_refuel %}
<ul>
{% for vehicle_id in vehicle_refuel %}
<p>
<li>Les pleints fait pour {{ vehicle_id.grouper}} sont:</li>
</p>
<table border="2">
<thead class="table-dark">
<th colspan="2">Driver name :</th>
<th>Driver number :</th>
<th>Gaz Station : </th>
<th>Date :</th>
<th>Kilometrage :</th>
<th>Quantity of Fuel: </th>
<th>Litre Price (Dh): </th>
<th>Totale (Dh)</th>
<th>City</th>
</thead>
<tbody id="body-table"><tr>
{% for refuel in vehicle_id.list %}
<tr>
<td colspan="2">{{ refuel.driver_id.first_name}} {{ refuel.driver_id.last_name }}</td>
<td>{{ refuel.driver_id.registration_number }}</td>
<td>{{ refuel.gaz_station_id.name}}</td>
<td>{{ refuel.date_time_creation }}</td>
<td>{{ refuel.odometer_reading }}</td>
<td>{{ refuel.fuel_quantity }}</td>
<td>{{ refuel.fuel_unit_price }}</td>
<td>{{ refuel.fuel_quantity|mul:refuel.fuel_unit_price }}</td>
<td>{{ refuel.gaz_station_id.city_id.city }}</td>
</tr>
{% endfor %}
</tbody>
{% endfor %}
</ul>
</div>
</div>
{% endblock content %}
You have two errors in your html
random <tr> element with no closing tag.
<tbody id="body-table"><tr>
{% for refuel in vehicle_id.list %}
no closing tag for <table>
</tr>
{% endfor %}
</tbody>
<!-- missing </table> here-->
{% endfor %}
</ul>
Because I can't run your code I have assumed that the <tr> tag is not supposed to be there.
Therefore, hopefully this fixes your problem.
{% extends 'base.html' %}
{% load mathfilters %}
{% block title %}
<title>Refuels Archive</title>
{% endblock title %}
{% block content %}
<div class="container">
<h1>La liste des gazoile archivé </h1>
<ul>
{% for date in date_list %}
<li>{{ date|date }}</li>
{% endfor %}
</ul>
<div>
<h1>All Refuels for {{ year|date:"Y" }}</h1>
{% regroup object_list by vehicle_id as vehicle_refuel %}
<ul>
{% for vehicle_id in vehicle_refuel %}
<p>
<li>Les pleints fait pour {{ vehicle_id.grouper}} sont:</li>
</p>
<table border="2">
<thead class="table-dark">
<th colspan="2">Driver name :</th>
<th>Driver number :</th>
<th>Gaz Station : </th>
<th>Date :</th>
<th>Kilometrage :</th>
<th>Quantity of Fuel: </th>
<th>Litre Price (Dh): </th>
<th>Totale (Dh)</th>
<th>City</th>
</thead>
<tbody id="body-table">
{% for refuel in vehicle_id.list %}
<tr>
<td colspan="2">{{ refuel.driver_id.first_name}} {{ refuel.driver_id.last_name }}</td>
<td>{{ refuel.driver_id.registration_number }}</td>
<td>{{ refuel.gaz_station_id.name}}</td>
<td>{{ refuel.date_time_creation }}</td>
<td>{{ refuel.odometer_reading }}</td>
<td>{{ refuel.fuel_quantity }}</td>
<td>{{ refuel.fuel_unit_price }}</td>
<td>{{ refuel.fuel_quantity|mul:refuel.fuel_unit_price }}</td>
<td>{{ refuel.gaz_station_id.city_id.city }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}
</ul>
</div>
</div>
{% endblock content %}
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.