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 %}
Related
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 a Django project that I'm trying to cobble together for a very basic survey that needs to be entered for demographic information. I've dummied up some data through the admin site in order to get my ListView working for the time being.
Unfortunately, I'm getting a strange response. I built the models.py to be a drop-down of a full spelled out and then to keep it small, I've made the actual storage in the db 1-3 characters. When I get my list view, one that uses 1 character to store for gender presents as (<django.db.models.fields.CharField>,), I would like for it to present as as the larger name of "Male", "Female", "Non-binary".
However, for my race and ethnicity fields which are 2 & 3 characters, those are returning as the actual storage for the DB (i.e, 'AA', 'NHP'). I'm more comfortable with SQL, so I'm not opposed to adding a table for a key as there would only be 11 entries for now, but it is possible that more things could be added down the line.
models.py:
from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User
# Create your models here.
class StuData(models.Model):
id_num = models.IntegerField(primary_key=True)
entry_date = models.DateTimeField('Date of Entry')
MALE = 'm'
FEMALE = 'f'
OTHER = 'x'
GENUNK = 'u'
GENDER_SELECTIONS = [
(MALE,'Male'),
(FEMALE,'Female'),
(OTHER,'Non-Binary'),
(GENUNK,'Unknown'),
]
gender = models.CharField(max_length=1, choices=GENDER_SELECTIONS),
## Build the selections for the race field
AFR_RACE = 'AA'
ASI_RACE = 'AS'
WHI_RACE = 'WH'
UNK_RACE = 'UN'
RACE_SELECTIONS = [
(AFR_RACE, 'African-American'),
(ASI_RACE, 'Asian/Pacific Islander'),
(WHI_RACE, 'White'),
(UNK_RACE, 'Unknown Race'),
]
race = models.CharField(max_length=2, choices=RACE_SELECTIONS)
## Build the selections for the ethnicity field
HSP = 'HIS'
NHP = 'NHP'
UNK = 'UNE'
ETHNICITY_SELECTIONS = [
(HSP, 'Hispanic Origin'),
(NHP, 'Not of Hispanic Origin'),
(UNK, 'Unknown Ethnicity'),
]
ethnicity = models.CharField(max_length=10, choices=ETHNICITY_SELECTIONS)
stu_count = models.IntegerField(default=1)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ["cad_num"]
def __str__(self):
return self.name
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from mvstop.models import StuData
from django.views.generic.list import ListView
from django.views.generic.edit import UpdateView, CreateView
# Create your views here.
class StuDataList(ListView):
model = StuData
template = "myapp/studata_list.html"
fields = ""
paginate_by = 25
def Meta():
ordering = ['id_num']
def __str__(self):
return self.name
studata_list.html:
<!DOCTYPE html>
{% extends "./base.html" %}
{% block content %}
<h3>Most recent entries</h3>
<table id="studata">
<tr>
<th>ID Number</th>
<th>Entry Date</th>
<th>Gender</th>
<th>Race</th>
<th>Ethnicity</th>
<th>Count</th>
</tr>
{% for stu in studata_list %}
<tr>
<tr>
<td>{{ stu.id_num }}</td>
<td>{{ stu.entry_date }}</td>
<td>{{ stu.gender }}</td>
<td>{{ stu.race }}</td>
<td>{{ stu.ethnicity }}</td>
<td>{{ stu.occupants }}</td>
</tr>
{% endfor %}
</tr>
</table>
{% endblock %}
Django have build in method for that:
get_FIELD_display()
so in your template:
{% for stu in studata_list %}
<tr>
<tr>
<td>{{ stu.id_num }}</td>
<td>{{ stu.entry_date }}</td>
<td>{{ stu.get_gender_display }}</td>
<td>{{ stu.get_race_dispaly }}</td>
<td>{{ stu.get_ethnicity_display }}</td>
<td>{{ stu.occupants }}</td>
</tr>
{% endfor %}
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.
In the code below the inner forloop is not working
<tbody>
{% for rec in medrec %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ rec.date }}</td>
<td>{{ rec.disease }}</td>
<td>{{ rec.treatment }}</td>
<td> {% for n in medicine.forloop.parentforloop.counter0 %}
{{ n.medicine }}
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
The code above generates a table. Each rec has a array of medicines.
Like for the rec.forloop.counter where forloop.counter == 1 there will objects in the medicine array index [0].
How do i print it?
def profile(request,rid):
patient = Patient.objects.get(pk=rid)
medic = MedicalRec.objects.filter(patient=patient)
i=0
a=[]
for n in medic:
a.append(medicine.objects.filter(Rec= n))
print(a)
if patient:
return render(request,'patient.html',{
'medrec' : medic,
'pat' : patient,
'medicine' : a
})
else:
return 'patient not found'
Models
from django.db import models
# Create your models here.
class Patient(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
address = models.TextField()
contact = models.CharField(max_length=15)
def __str__(self):
return self.name
class Stock(models.Model):
name = models.CharField(max_length=100)
quantity = models.IntegerField()
expiry = models.DateField()
price = models.IntegerField()
def __str__(self):
return self.name
class MedicalRec(models.Model):
patient = models.ForeignKey(Patient)
date = models.DateField()
disease = models.TextField()
treatment = models.TextField()
medicine = models.ForeignKey(Stock)
def __str__(self):
return str(self.date)
class medicine(models.Model):
Rec = models.ForeignKey(MedicalRec,related_name='med_set')
medicine = models.ForeignKey(Stock)
def __str__(self):
return str(self.Rec.date)
class Billing(models.Model):
name = models.ForeignKey(Stock)
rate = models.IntegerField()
Date = models.DateField()
def __str__(self):
return self.id
You don't have to create the list yourself. Django creates a reverse relation for you. It will be named medicine_set, but now that you're showing your models you have overridden it to be med_set. So you do not have to create a list in your view. You can use the related manager in your template:
view:
def profile(request, rid):
patient = get_object_or_404(Patient, pk=rid)
medic = MedicalRec.objects.filter(patient=patient)
return render(request, 'patient.html', {
'pat': patient,
'medrec': medic,
})
Template:
<tbody>
{% for rec in medrec %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ rec.date }}</td>
<td>{{ rec.disease }}</td>
<td>{{ rec.treatment }}</td>
<td>
{% for medicine in medrec.med_set.all %}
{{ medicine }}
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
I modified melvyn's answer and it worked
<tbody>
{% for rec in medrec %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ rec.date }}</td>
<td>{{ rec.disease }}</td>
<td>{{ rec.treatment }}</td>
<td>
{% for medicine in rec.med_set.all %}
{{ medicine.medicine }},
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
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