Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

display data without using a loop Django

How do I forgo the loop and display only one product represented below?

{data.title }}



 {% for data in data %}
    <h3 class="my-4 border-bottom pb-1">{{data.title }}</h3>
    <div class="row">
        {% endfor %}

I tried to use:

<h3 class="my-4 border-bottom pb-1">{{data.title }}</h3>
    <div class="row">

I got a blank section, the loop works perfectly though. Here is the views function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

booking_detail(request, slug, id):
        booking=Bookings.objects.all().order_by('-id')
        return render(request,'booking_detail.html',{'data':booking})

model

class Bookings(models.Model):
    title=models.CharField(max_length=200)
    image=models.ImageField(upload_to="rooms_imgs")
    slug=models.CharField(max_length=400)
    detail=models.TextField()
    features=models.TextField()
    location=models.ForeignKey(Location, on_delete=models.CASCADE)
    category=models.ForeignKey(Category, on_delete=models.CASCADE)
    hostel=models.ForeignKey(Hostel, on_delete=models.CASCADE)
    amenities=models.ForeignKey(Amenities, on_delete=models.CASCADE)
    roomsizes=models.ForeignKey(RoomSizes,on_delete=models.CASCADE)
    status=models.BooleanField(default=True)
    is_featured=models.BooleanField(default=False)
    is_availabe=models.BooleanField(default=True)
    

url

path('booking/<str:slug>/<int:id>',views.booking_detail,name='booking_detail'),

>Solution :

As I understand this view function is used only for one booking

booking_detail(request, slug, id):
        booking=Bookings.objects.all().order_by('-id')
        return render(request,'booking_detail.html',{'data':booking})

So it is better to change it to retrieve only one record, not list

from django.shortcuts import get_object_or_404


def booking_detail(request, slug, id):
    booking=get_object_or_404(Bookings, pk=id, slug=slug) 
    return render(request,'booking_detail.html',{'booking': booking})

And then in HTML just:

<h3 class="my-4 border-bottom pb-1">{{ booking.title }}</h3>
<div class="row">

Documentation
https://docs.djangoproject.com/en/4.0/topics/http/shortcuts/#get-object-or-404

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading