Cannot access foreign key elements in html templates DJANGO - python

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

Related

Django: Show data from current user

I'm having trouble displaying data from current user. It shows all the shifts that was given to other users also. I don't have any idea how to do this. Below is my code.
models.py
class User(models.Model):
user_name = models.CharField(max_length=32, unique=True)
pass_word = models.CharField(max_length=150)
is_active = models.BooleanField(default=True)
class Rostering(models.Model):
name = models.CharField(max_length=64)
begin_time = models.TimeField(default="")
end_time = models.TimeField(default="")
is_active = models.BooleanField(default=True)
class RosteringUser(models.Model):
rostering_user = models.ForeignKey(Rostering, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
views.py
def my_shift(request):
if request.method == 'GET':
queryset = RosteringUser.objects.all()
if queryset:
for obj in queryset:
id = Rostering.objects.get(rosteringuser=obj.id)
obj.id = id
return render(request, 'my_shift.html', {'queryset': queryset})
my_shift.html
{% for obj in queryset %}
<tr>
<td>{{ obj.user.user_name }}</td>
<td>{{ obj.id.name }}-{{ obj.id.begin_time }}</td>
<td>{{ obj.id.name }}-{{ obj.id.end_time }}</td>
</tr>
{% endfor %}
Thank you in advance!
Simply you can try like this:
if queryset:
for obj in queryset:
id = Rostering.objects.get(rosteringuser=obj.id)
obj.id = id
querysets = obj
return render(request, 'my_shift.html', {'querysets': querysets})
And in templates:
{% for object in querysets %}
<tr>
<td>{{ object.user.user_name }}</td>
<td>{{ object.id.name }}-{{ object.id.begin_time }}</td>
<td>{{ object.id.name }}-{{ object.id.end_time }}</td>
</tr>
{% endfor %}
def my_shift(request):
if request.method == 'GET':
rost_id = RosteringUser.objects.filter(user_id=request.user.id).values("rostering_user_id").first()
if rost_id :
data = Rostering.objects.get(id=rost_id['rostering_user_id'])
return render(request, 'my_shift.html', {'queryset': data })
in template you can directly display logged in username {{ request.user.first_name }}

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 to assign few objects to one user

I want to have template page with object(orders) list (another list, for another user). Like relations one to many. Where do i need to define that objects(order)(for exemple by id: order_id=1 and order_id=3) is assigned to user(driver) with id=1 etc?
I was trying to create Driver class and than set atribute driver in order Class like this.
form.py
class OrderForm(forms.Form):
telephone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'.")
airport = forms.ChoiceField(choices=AIRPORT_CHOICES) ### Jeśli lotnisko jest celem podróży
direction = forms.ChoiceField(choices=DIRECTION_CHOICES) ## to pick_up < plane i odwrotnie!!!
adress = forms.CharField()
client = forms.CharField()
telephone = forms.CharField(validators=[telephone_regex])
flight_number = forms.CharField()
plane = forms.DateTimeField(input_formats=['%Y-%m-%d'])
pick_up = forms.DateTimeField(input_formats=['%Y-%m-%d'])
gate = forms.CharField()
company = forms.ChoiceField(choices=COMPANY_CHOICES)
driver = forms.ChoiceField(choices=DRIVER_CHOICES)
models.py
class Driver(models.Model):
name = models.CharField(max_length=30)
tel = models.CharField(max_length=17)
class Order(models.Model):
telephone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format:
'+999999999'.")
airport = models.CharField(max_length=10, choices=AIRPORT_CHOICES)
direction = models.CharField(max_length=7, choices=DIRECTION_CHOICES)
adress = models.CharField(max_length=100, null=False, blank=False)
client = models.CharField(max_length=50, null=False, blank=False)
telephone = models.CharField(validators=[telephone_regex], max_length=17, blank=False)
flight_number = models.CharField(max_length=7)
plane = models.DateTimeField(null=True)
pick_up = models.DateTimeField(null=True)
gate = models.CharField(max_length=10, null=True, blank=True)
comapny = models.CharField(max_length=50, choices=COMPANY_CHOICES)
driver = models.ForeignKey(Driver, on_delete=models.CASCADE)
order_list.html
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<h1>Hi {{ user.username }}! Have a good tips!</h1>
{% else %}
<h1>You have to login to see your orders list</h1>
{% endif %}
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">client</th>
<th scope="col">telephone</th>
<th scope="col">flight number</th>
<th scope="col">airport</th>
<th scope="col">direction</th>
<th scope="col">adress</th>
<th scope="col">gate</th>
<th scope="col">plane</th>
<th scope="col">pick up</th>
</tr>
</thead>
{% for order in orders %}
<tbody>
<tr>
<th scope="row">{{ order.id }}</th>
<td>{{ order.client }}</td>
<td>{{ order.telephone }}</td>
<td>{{ order.flight_number }}</td>
<td>{{ order.airport }}</td>
<td>{{ order.direction }}</td>
<td>{{ order.adress }}</td>
<td>{{ order.gate }}</td>
<td>{{ order.plane }}</td>
<td>{{ order.pick_up }}</td>
<td>{{ order.driver }}</td>
</tr>
</tbody>
{% endfor %}
</table>
{% endblock %}
views.py
class OrderView(View):
def get(self, request, id):
orders = Order.objects.get(id=id)
users = User.object.get(id=id)
ctx = {
'orders': orders,
'users': users
}
return render(request, 'order.html', ctx)
class OrderListView(View):
def get(self, request):
form = OrderForm()
orders = Order.objects.all()
ctx = {'form': form, 'orders': orders}
return render(request, 'orders/order_list.html', ctx)
class AddOrderView(View):
def get(self, request):
form = OrderForm()
return render(request, 'orders/add_order.html', {'form': form})
def post(self, request, *args, **kwargs):
form = OrderForm(request.POST)
if form.is_valid():
order = Order.objects.create(airport=form.cleaned_data['airport'],
direction=form.cleaned_data['direction'],
adress=form.cleaned_data['adress'],
client=form.cleaned_data['client'],
telephone=form.cleaned_data['telephone'],
flight_number=form.cleaned_data['flight_number'],
plane=form.cleaned_data['plane'],
pick_up=form.cleaned_data['pick_up'],
gate=form.cleaned_data['gate'],
driver=form.cleaned_data['driver'])
return render(request, 'orders/add_order.html', {'form': form})
I expect to get form when i can input new order and select driver but I'm geting this:
http://dpaste.com/0PD363H

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