def __init__
def __init__

Reputation: 1066

returning more than one variable in render of django

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.

Upvotes: 0

Views: 276

Answers (3)

Ankush Rathour
Ankush Rathour

Reputation: 457

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)

Upvotes: 1

sebtheiler
sebtheiler

Reputation: 2557

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}
)

Upvotes: 1

Sandeep Rawat
Sandeep Rawat

Reputation: 214

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

Upvotes: 1

Related Questions