Home > OS >  How can I return a context from views.py in different html files in Django?
How can I return a context from views.py in different html files in Django?

Time:11-27

So, I have a method called 'room' in my views.py file.

I can only access this room on my room.html page as I'm returning it there but I would like to use this data on my index page as well.

How can I do that?

Views.py

def room(request):
    rooms = Rooms.objects.all()
    photos = RoomImage.objects.all()
    context = {'rooms':rooms, 'photos':photos}    
    return render(request, 'hotelbook/room.html', context)

CodePudding user response:

I can only access this room on my room.html page as I'm returning it there but I would like to use this data on my index page as well.

Just pass Rooms.objects.all() also in that view which renders the index.html template.

Below is an example.

def index(request):
    rooms = Rooms.objects.all()
    photos = RoomImage.objects.all()
    context = {'rooms':rooms, 'photos':photos}    
    return render(request, 'hotelbook/index.html', context)

Now, you can also use rooms in index.html template.

CodePudding user response:

You can do one thing, just create a simple utility function in views.py for getting all rooms.

create utils.py file in django application:

# utils.py
def get_all_rooms():
    all_rooms = Room.objects.all()
    all_photos = RoomImage.objects.all()
    return {"rooms": all_rooms, "photos": all_photos}

Then, import utils in views.py file

# views.py

from .utils import get_all_rooms

data = get_all_rooms()

def room(request):
    return render(request, "room.html", {"data": data})

def index(request):
    return render(request, "index.html", {"data": data})

This can be very efficient as we are calling cahced result instead of firing new db query!

  • Related