Home > Net >  returning more than one variable in render of django
returning more than one variable in render of django

Time:07-05

I define home request in views.py,

db=client.inventory_data
def home(request):
    collection_data_1 = db['orders']
    mydata = list(collection_data.find())
    return render(request,'home.html',{'mydata': mydata})

The above function works fine but when I try to return one more list, it does not work.

def home(request):
    collection_data_1 = db['orders']
    collection_data_2 = db['product']
    mydata = list(collection_data_1.find())
    product_data = list(collection_data_2.find())
    return render(request,'home.html',{'mydata': mydata},{'product_data':product_data})

I want to return both the list, how can we achieve this? looking for kind help.

CodePudding user response:

You can simply combine the two dictionaries into one: {'mydata': mydata, 'product_data': product_data}

def home(request):
    collection_data_1 = db['orders']
    collection_data_2 = db['product']
    mydata = list(collection_data_1.find())
    product_data = list(collection_data_2.find())

    return render(request,'home.html',{'mydata': mydata, 'product_data': product_data})

The reason that it didn't work when you passed in the two dictionaries separately is because render accepts context (a dictionary) as the third argument and content_type (a string) as the fourth argument, so when you passed in two dictionaries, you were passing in a dictionary as the content_type.

If it helps, here's what you originally had with the variable names annotated:

render(
   request=request,
   template_name='home.html',
   context={'mydata':mydata},
   content_type={'product_data':product_data},
)

And here's what you have now:

render(
   request=request,
   template_name='home.html',
   context={'mydata': mydata, 'product_data': product_data}
)

CodePudding user response:

def home(request):
    # ...
    return render(request,'home.html',{'mydata': mydata, 'product_data':product_data})

CodePudding user response:

def home(request):
    collection_data_1 = db['orders']
    collection_data_2 = db['product']
    mydata = list(collection_data_1.find())
    product_data = list(collection_data_2.find())
    context = {
     'mydata': mydata,
     'product_data': product_data
    }
    return render(request,'home.html', context=context)
  • Related