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
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
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.
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 %}
I'm new to django-python so I need extra details. All I need is to provide monthly report in a pdf form and a yearly report that also in pdf form.
From my model.py
class Case(models.Model):
case_number = models.CharField(max_length=50, blank=True, null=True, unique=True)
reference_choice = (
('Personal', 'Personal'),
('Court', 'Court'),
)
reference = models.CharField(max_length=20, choices=reference_choice, null=True)
date_of_filing = models.DateField('Date of Filing (mm/dd/yyyy)*', blank=True, null=True)
official_receipt = models.CharField(max_length=50, blank=True, null=True,)
complainant = models.CharField(max_length=150)
respondent = models.CharField(max_length=150)
case_title = models.CharField(max_length=200)
On my views.py
class GeneratePDF(View):
model = Case
def get(self, request, *args, **kwargs):
cases = Case.objects.filter.all()
context = {
'date': date,
'cases': cases,
}
pdf = render_to_pdf('pdf/monthly_report.html', context)
if pdf:
response = HttpResponse(pdf, content_type='application/pdf')
filename = 'monthly_report_%s.pdf' %('month')
content = 'inline; filename="%s"' % (filename)
response['Content-Disposition'] = content
return response
return HttpResponse('Not Found')
and on my monthly_report.html
<div class="container mt-4">
<table class="table-" style="width:1200px">
<thead class="thead-light">
<tr>
<th scope="col">Case Number</th>
<th scope="col">Complainant</th>
<th scope="col">Respondent</th>
<th scope="col">Case Title</th>
<th scope="col">Action Taken</th>
<th scope="col">Remarks</th>
</tr>
</thead>
<tbody>
{% for case in cases %}
<tr>
<td>{{ case.case_number }}</td>
<td>{{ case.complainant }}</td>
<td>{{ case.respondent }}</td>
<td>{{ case.case_title }}</td>
<td>{{ case.mediated| yesno }}</td>
<td>{{ case.remarks }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
On my code I only get all the data but it is not filtered.
so you should change your query to the correct filter.for example you can do this
cases=Case.objects.all().filter(date_of_filing = sometime)
on the line Case.objects.filter.all() you can filter your results. however it does not seem like you are doing that?
an example:
from django.utils import timzeone
Case.objects.filter(date__gte=timezone.now()-timezone.timedelta(days=1))
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>