jayt
jayt

Reputation: 768

Django - retrieve information if only it's needed

I'm looking at building a site where you have a detail view of an object, and more data about that object can be shown to the user by clicking to open a modal pop up box. I was wondering how, in Django, this data can only be loaded if the user chooses to open the modal box - otherwise there's no point in it being there.

def detail_view(request):
    ...
    extra_data = Object.objects.all().values_list('rating', flat=True) # Only required if a user open the modal box
    return render(request, 'detail.html', {'extra_data':extra_data})

Any ideas on how this might be achieved whilst using as little JavaScript as possible?

Upvotes: 0

Views: 47

Answers (1)

Abhishek Vijayan
Abhishek Vijayan

Reputation: 753

This is a very broad question, although the following is a generic structure of how you can achieve this. The code below is just for reference. It is just to demonstrate the structure. You need two views, first view will fetch the basic info for all items. The second view fill fetch the additional details for the selected item.

The assumption is that you will have a button for opening the modal, to show the more details.

The javascript is listening to the click event on that button, and it is fetching more details that is to be displayed from the server, and then displaying it in the modal container.

Disclaimer: This is not the most optimal way to do this, this is just a quick and dirty solution.

//Assuming there is a button with id myButton using which user will toggle modal

$("#myButton").on("click", function(e) {
  e.preventDefault();
  var modal = null;//whatver the modal is
  var model_id = 1;//store the id of the model in a accessible location and load it here
  var modalContainer = $("#modalContent") // the element which is the container of the modal which will hold its contents
  $.ajax({
  url: "/get_item_detail", //this url should call viewB
  type: "GET",
  data: {
   "id": model_id
  },
  success: function(response) {
    var html = "<div></div>" //generate your html content for the modal container
    modalContainer.html(html); //put the generated html content inside the modal Container
    modal.open(); //open the modal here
    
  },
  error: function(response) {
  
  }
  })
});
from django.shortcuts import render
from django.http import JsonResponse
import json

def viewA(request):
  #Fetch the basic info for all objects
  items = Sample.objects.all()
  return render(reqeust, "template.html", {
  "items": items
  })
  
def viewB(request):
  #Fetch the additional detail of the concerned object
  id = request.GET.get("id", None) #get id or if no id, set None
  detailed_item = Sample.objects.get(id=id)
  return JsonResponse(json.loads(detailed_item), safe=False)

Upvotes: 1

Related Questions