Home > OS >  display data without using a loop Django
display data without using a loop Django

Time:03-29

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

{data.title }}



 {% for data in data %}
    <h3 >{{data.title }}</h3>
    <div >
        {% endfor %}

I tried to use:

<h3 >{{data.title }}</h3>
    <div >

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

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'),

CodePudding user response:

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 >{{ booking.title }}</h3>
<div >

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

  • Related