Django template regorup - python

I want to regroup this on the basis of ingredients.
this is my sample result which I want
Just like the below picture as there is more than one certificate so I am showing them in one row.
Ingredient_name, all the stop_name associated with that ingredient,
all the stop_longitude associated with that ingredient and so on in one table row.
Right now its showing like this and you can see that the ingredient name is repeating .
model
class SupplyChainStops(models.Model):
ingredient = models.ForeignKey(Ingredients, null=True, on_delete=models.CASCADE)
stop_name = models.CharField(max_length=1024, null=True, blank=True)
stop_longitude = models.CharField(max_length=500, null=True, blank=True)
stop_latitude = models.CharField(max_length=500, null=True, blank=True)
is_supplier = models.BooleanField(default=False, blank=True, null=True)
def __str__(self):
return f'{self.stop_name}'
query
items = SupplyChainStops.objects.all()
template
{% for item in items %}
<tr class="text-black">
<td>{{ item.ingredient }}</td>
<td>{{ item.stop_name }}
<td>{{ item.stop_longitude }}
<td>{{ item.stop_latitude }}
This is my DB structure
This is my desired output

You can set the related_name for ForeignKey field.
class SupplyChainStops(models.Model):
ingredient = models.ForeignKey(Ingredients, null=True, on_delete=models.CASCADE, related_name="supply_chain_stops")
in view:
each_row = []
ing_ids = []
sup = SupplyChainStops.objects.all()
for each_sup in sup:
ing_ids.append(each_sup.ingredient.id)
ing_ids = list(set(ing_ids))
sch = []
for each_ing_id in ing_ids:
sch.append(SupplyChainStops.objects.filter(ingredient__id= each_ing_id).last())
for each in sch:
stop_names_list = []
stop_longitude_list = []
stop_latitude_list = []
mi_list = each.ingredient.supply_chain_stops.all()
for each_mi in mi_list:
stop_names_list.append(each_mi.stop_name)
stop_longitude_list.append(each_mi.stop_longitude)
stop_latitude_list.append(each_mi.stop_latitude)
row_list = [each.ingredient, stop_names_list, stop_longitude_list, stop_latitude_list]
each_row.append(row_list)
context = {
"items": each_row
}
in template:
{% for item in items %}
<tr class="text-black">
<td>{{ item.0 }}</td>
<td>{{ item.1|join:", " }}</td>
<td>{{ item.2|join:", " }}</td>
<td>{{ item.3|join:", " }}</td>
</tr>
{% endfor %}

Related

Cannot access foreign key elements in html templates DJANGO

Views:
def search_devis(request):
devis = Devis.objects.all()
commercial = User.objects.all()
client = Client.objects.all()
context={
'devis': devis,
'commercial': commercial,
'client_': client,
}
return render(request, "manage_devis/search_devis.html",context )
Models:
class Devis(models.Model):
titre = models.CharField(max_length=30, )
date_ecriture = models.DateField(auto_now_add=True)
date_expiration = models.DateField()
client = models.ForeignKey(Client, name="CLIENT_FK", default=1 ,on_delete=models.SET_DEFAULT)
total = models.DecimalField(max_digits=10, decimal_places=2)
commercial = models.ForeignKey(User, name="COMMERCIALFK", default=1 ,on_delete=models.SET_DEFAULT)
def __str__(self):
return "DV"+str(self.pk)
Templates:
{% for devis_ in devis %}
<tr>
<th scope="row">DV{{devis_.id }}</th>
<td>{{ devis_.date_ecriture }}</td>
<td>{{ devis_.date_expiration }}</td>
<td>{{devis_.client.nom}}</td>
<td>{{ devis_.total}} DH</td>
<td>{{ devis_.commercial.last_name}}</td>
</tr>
{% endfor %}
I can't display the attributes of the foreign key object, no value in it.
nothing appear in the column.
I'm using postgresql database.
First of all, try removing the name="CLIENT_FK" in the model and then make the migration (python manage.py makemigrations and python manage.py migrate).
Your model now should look something like:
class Devis(models.Model):
titre = models.CharField(max_length=30, )
date_ecriture = models.DateField(auto_now_add=True)
date_expiration = models.DateField()
client = models.ForeignKey(Client, default=1 ,on_delete=models.SET_DEFAULT)
total = models.DecimalField(max_digits=10, decimal_places=2)
commercial = models.ForeignKey(User, default=1 ,on_delete=models.SET_DEFAULT)
def __str__(self):
return "DV"+str(self.pk)
After that, you can iterate in your forloop, please, avoid using something like devis_. I suggest you to use a forloop like this:
{% for dev in devis %}
<tr>
<th scope="row">DV{{dev.id }}</th>
<td>{{ dev.date_ecriture }}</td>
<td>{{ dev.date_expiration }}</td>
<td>{{dev.client.nom}}</td>
<td>{{ dev.total}} DH</td>
<td>{{ dev.commercial.last_name}}</td>
</tr>
{% endfor %}
Try {% for devis in object.devis_set.all %}
And don’t use _ at the end of the devis

i have to make a relation between movie and actor without using manytomany field i have to use only foreign key in django i've write this code so far

models.py
class Movielist(models.Model) :
Title = models.CharField(max_length=1000)
Description = models.TextField(blank=True)
ReleaseDate = models.DateTimeField(verbose_name='Release Date', blank=True)
# NoOfActors = models.IntegerField()
Upvote = models.IntegerField(default=0)
Downvote = models.IntegerField(default=0)
def __str__(self):
return self.Title
class Actorlist(models.Model):
Name = models.CharField(max_length=1000)
DateofBirth = models.DateTimeField(verbose_name='Date of Birth',blank=True)
# NoOfActors = models.IntegerField()
def __str__(self):
return self.Name
class ActorInMovie(models.Model):
Movie = models.ForeignKey(Movielist, default=1, on_delete=models.CASCADE, blank=True)
Actor = models.ForeignKey(Actorlist, default=1, on_delete=models.CASCADE, blank=True)
def __str__(self):
return self.Movie.Title
views.py
def Movie_Detail(request):
MovieName = Movielist.objects.all()
tablelist = ActorInMovie.objects.all()
return render(request, 'Collection/index.html', {'MovieName':MovieName, 'tablelist':tablelist})
index.html
<table border="solid">
<th>Name</th>
<th>Release Date</th>
<th>Actors</th>
{% for data in MovieName %}
<tr>
<td>{{ data.Title }}</td>
<td>{{ data.ReleaseDate }}</td>
<td>
<ul>
{% for name in tablelist %}
<li>{{ name.Actor.Name }}</li>
{% endfor %}
</ul>
</td>
</tr>
{% endfor %}
</table>
**i have getting this out put can any any one tell me how to filter this data only my movie id i would like if someone come and help me in solving this problem
[this is the output what i am getting but i want filter actors name by movielist.id][1]
[1]: https://i.stack.imgur.com/BlAuP.png**
You are selecting all the objects in ActorInMovie into tablelist, and not just the related ones. You don't need the tablelist at all. Instead:
{% for data in MovieName %}
<tr>
<td>{{ data.Title }}</td>
<td>{{ data.ReleaseDate }}</td>
<td>
<ul>
{% for movie_actor in data.ActorInMovie %}
<li>{{ movie_actor.Actor.Name }}</li>
{% endfor %}
</ul>
</td>
</tr>
{% endfor %}
You might also need to use related_name in your ActorInMovie model to tell django how you'll identify the related fields:
Movie = models.ForeignKey(Movielist, default=1, on_delete=models.CASCADE, blank=True, related_name='ActorInMovie)
Since you're going to print all the actors of every movie, it's a good idea to use prefetch_related(Another ref) to achieve better performance, but it's not required if you don't have a lot of data.

Iterate over several querysets in django template with nested loop

I am making a hotell-page, and have made models for bookings and rooms.
I want to display the bookings related to a room in a table, and have the related bookings laying under the spesific room.
I show the code from the views.py file here:
def vaskehjelp(response):
available_rooms = Room.objects.filter(available=True)
room_nums = []
context = {}
for room in available_rooms:
related_bookings = Booking.objects.filter(room=room)
if related_bookings:
room_nums.append(room.room_no)
context[room.room_no] = related_bookings
context["room_nums"] = room_nums
context["available_rooms"] = available_rooms
print(context)
return render(response, "../templates/se_vaskbare_rom.html", context)
and the code from my template file here:
<table class="table table-striped table-dark">
<tr class="thead-dark">
<th scope="col">Room No.</th>
<th scope="col">Capacity</th>
<th scope="col">Room Type</th>
</tr>
{% for item in available_rooms %}
<tr scope="row">
<td>{{ item.room_no }}</td>
<td>{{ item.capacity }}</td>
<td>{{ item.room_type }}</td>
</tr>
{% if item.room_no in room_nums %}
{% for booking in item.room_no %}
<h1></h1>
<tr scope="row">
<td>{{ booking.cin_date }}</td>
<td>ku</td>
<td>{{ booking.cout_date }}</td>
</tr>
{% endfor %}
{% endif %}
{% endfor %}
</table>
The problem is that the booking-element in the template code doesent seem to work. I dont manage to access the lists of bookings related to the current selected room. As you see i have an outer for loop to iterate over the rooms, and then the inner for loop iterate over the related bookings (only in case that room is in the "room_nums" list. The problem is (i think) that the for booking in item.room_no doesnt work, i dont get any info from the booking variable at least...
In the table i should have had the check in and check out dates in the left and right column, but i dont get this information from the booking variable...
ps: the idea is that item.room_no is referrering to a list in the context dictionary. I have tried other things, but this is the closest i have come.
Here are the models:
class Room(models.Model):
room_choices = [('S', 'Single Occupancy'), ('D', 'Double Occupancy'), ('F', 'Firemannsrom')]
room_no = models.CharField(max_length=5) # primary key
available = models.BooleanField(default=False)
capacity = models.IntegerField(default=None)
room_type = models.CharField(choices=room_choices, max_length=1, default=None)
price = models.IntegerField( blank=True, null=True)
def __str__(self):
return "Romnr: " + str(self.room_no) + " -- type:" + str(self.room_type)
and
class Booking(models.Model):
#defaultRom = Room.objects.get(room_no='100')
#defaultRomID = defaultRom.id
room_choices = [('S', 'Single Occupancy'), ('D', 'Double Occupancy'), ('F', 'Firemannsrom')]
bookingid = models.AutoField(db_column='BookingID', primary_key=True) # Field name made lowercase.
guest = models.ForeignKey('auth.User', on_delete=models.CASCADE) # eller settings.AUTH_USER_MODEL
cin_date = models.DateField(db_column='CIN_Date', blank=True, null=True,
verbose_name='Check-In Date') # Field name made lowercase.
cout_date = models.DateField(db_column='COUT_Date', blank=True, null=True,
verbose_name='Check-Out Date') # Field name made lowercase.
room_type = models.CharField(choices=room_choices, max_length=1, default=None)
room = models.ForeignKey('Room', on_delete=models.CASCADE, db_column='Room', default=None)
class Meta:
managed = True
db_table = 'Booking'
def __str__(self):
return "Bruker: " + self.guest.__str__() + " -- id:" + str(self.bookingid) + " -- Inndato: " + self.cin_date.__str__() + " -- Utdato: " + self.cout_date.__str__() + " -- " + self.room.__str__()
Here is the the result of print(context):
{'100': <QuerySet [<Booking: Bruker: email -- id:27 -- Inndato: 2020-03-27 -- Utdato: 2020-03-29 -- Romnr: 100 -- type:S>]>, '103': <QuerySet [<Booking: Bruker: olaNordmann -- id:26 -- Inndato: 2020-03-07 -- Utdato: 2020-03-15 -- Romnr: 103 -- type:D>]>, 'room_nums': ['100', '103'], 'available_rooms': <QuerySet [<Room: Romnr: 100 -- type:S>, <Room: Romnr: 103 -- type:D>, <Room: Romnr: 106 -- type:F>, <Room: Romnr: 101 -- type:S>]>}
Thanks in advance!
You are referencing to CharField defined in Room class instead of Booking queryset
a quick solution might be to change the code in a following way:
{% for booking in item.related_bookings %}
<h1></h1>
<tr scope="row">
<td>{{ booking.cin_date }}</td>
<td>ku</td>
<td>{{ booking.cout_date }}</td>
</tr>
{% endfor %}
def vaskehjelp(response):
available_rooms = Room.objects.filter(available=True)
context = {}
for room in available_rooms:
related_bookings = Booking.objects.filter(room=room)
if related_bookings:
room_nums.append(room.room_no)
room.related_bookings = related_bookings
context["room_nums"] = room_nums
context["available_rooms"] = available_rooms
print(context)
return render(response, "../templates/se_vaskbare_rom.html", context)
But I believe that the easiest solution is the following one:
def vaskehjelp(response):
context = {}
available_rooms = Room.objects.filter(available=True).prefetch_related('Room')
context["available_rooms"] = available_rooms
return render(response, "../templates/se_vaskbare_rom.html", context)
{% for item in available_rooms %}
<tr scope="row">
<td>{{ item.room_no }}</td>
<td>{{ item.capacity }}</td>
<td>{{ item.room_type }}</td>
</tr>
{% for booking in item.Room %}
<h1></h1>
<tr scope="row">
<td>{{ booking.cin_date }}</td>
<td>ku</td>
<td>{{ booking.cout_date }}</td>
</tr>
{% endfor %}
{% endfor %}

How can I style table data differently according to the cell value?

I am new to django and I try to stylize a cell data according to it's value but not working.
The StatusPorumbei model has many objects stored and for each value, I wand another badge class.How can I take each value in StatusPorumbei and giving to it other class? First is the model, next is the template and last is the view function.
class StatusPorumbei(models.Model):
status = models.CharField(max_length=25, null=False, blank=False, unique=True)
def __str__(self):
return self.status
class Meta:
verbose_name = "Status"
verbose_name_plural = "Statusuri"
ordering = ['status']
class Porumbei(models.Model):
id_porumbel = models.AutoField(primary_key=True)
serie_inel = models.CharField(max_length=25, null=False, blank=False, unique=True)
anul = models.CharField(max_length=4, null=False, blank=False)
culoare = models.ForeignKey(CuloriPorumbei, on_delete=models.CASCADE, null=False, blank=False)
culoare_ochi = models.ForeignKey(CuloriOchi, on_delete=models.CASCADE, null=False, blank=False)
sex = models.ForeignKey(Gender, on_delete=models.CASCADE)
ecloziune = models.DateField(null=True, blank=True)
rasa = models.CharField(max_length=50, null=True, blank=True)
linie = models.CharField(max_length=50, null=True, blank=True)
nume = models.CharField(max_length=50, null=True, blank=True)
tata = models.CharField(max_length=25, null=True, blank=True)
mama = models.CharField(max_length=25, null=True, blank=True)
compartiment = models.ForeignKey(Compartimente, on_delete=models.CASCADE, null=False, blank=False)
status = models.ForeignKey(StatusPorumbei, on_delete=models.CASCADE, null=False, blank=False)
<tbody>
{% for item in items %}
<tr class="table-active">
<td>{{ item.serie_inel }}</td>
<td>{{ item.anul }}</td>
<td>{{ item.culoare }}</td>
<td>{{ item.sex }}</td>
<td>{{ item.compartiment }}</td>
<td>{{ item.tata }}</td>
<td>{{ item.mama }}</td>
{% if item.status in sts %}
{% if "Activ" %}
<td><span class="badge badge-success">{{ item.status }}</span></td>
{% elif "Reproducător" %}
<td><span class="badge badge-indigo">{{ item.status }}</span></td>
{% endif %}
{% endif %}
<td>
<a href="#" class="mr-25" data-toggle="tooltip" data-original-title="Editare">
<i class="icon-pencil"></i> </a>
</td>
</tr>
{% endfor %}
</tbody>
def dashboard(request):
items = Porumbei.objects.all()
sts = StatusPorumbei.objects.all()
context = {
'items' : items,
'sts' : sts
}
template = loader.get_template("dashboard.html")
return HttpResponse(template.render(context, request))
Query on the item.status
{% if item.status.status == "Activ" %}
<td><span class="badge badge-success">{{ item.status }}</span></td>
{% elif item.status.status == "Reproducător" %}
<td><span class="badge badge-indigo">{{ item.status }}</span></td>
{% else %}
<td><span>{{ item.status.status }}</span></td>
{% endif %}

How to show field from another table using Django ORM?

I have a problem showing fields from another table, where two tables have relationships.
This is my first model:
class DataPribadiSiswa(models.Model):
SiswaID = models.AutoField(primary_key=True)
WaliKelasID = models.CharField(max_length=11, blank=True, null=True)
My second model:
class transaksi_kas(models.Model):
id_kas = models.AutoField(primary_key=True)
siswaID_trans = models.ForeignKey(DataPribadiSiswa, null=True, blank=True)
kelas = models.CharField(max_length=1, null=True, blank=True)
This is my views.py:
def transaksi_index(request):
transaksi = {}
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans')
return render(request, 'kastransaksi/transaksi_index.html', transaksi)
This is the template:
<table id="simple-table" class="table table-striped table-bordered table-hover">
<tr>
<th>No.</th>
<th>Nama</th>
<th>Wali Murid</th>
<th>Kelas</th>
</tr>
{% for kas in transaksikas%}
<tr>
<td>{{ forloop.counter }}</td>
<th>{{ kas.siswaID_trans }}</th>
<td>{{ kas.WaliKelasID }}</td>
<td>{{ kas.kelas }}</td>
</tr>
{% endfor %}
</table>
How do I show {{ kas.WaliKelasID }} from DataPribadiSiswa?
I think you mean to do the following
{{ kas.siswaID_trans.WaliKelasID }}
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans') after this you have to make query get or filter or other.
Example:
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans').get(id=id)
or
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans').filter(your query)
this is link

Categories