Reputation: 129
I would like to use a variable outside of the function in which it was defined. I have only ever passed data to different templates and have not had to reference that data afterwards so I am unsure as to how I should proceed.
views.py
def new_opportunity_company_id(request):
company = request.GET.get('selected_company')
company_obj = cwObj.get_company(company)
company_id = company_obj[0]['id']
return company_id
def new_opportunity_location(request):
for company_id in new_opportunity_company_id(request):
locations = cwObj.get_sites(company_id)
context = {'locations': locations}
return render(request, 'website/new_opportunity_location.html', context)
Any help would be greatly appreciated, I am still new to Django/Python. Thanks!
Upvotes: 0
Views: 228
Reputation: 196
Which variable are you referring to in this example? Also note your code is assuming that company_obj[0]['id']
is a list as your trying to iterate it in new_opportunity_location. The times you should be attempting to access a variable outside of a function scope do not come that often. They would either be a global, class variable or a function parameter thats passed. Other then that you may need to reconsider your approach to make your code more straight forward.
Following up to your comment...
def new_opportunity_location(request):
company = request.GET.get('selected_company')
company_obj = cwObj.get_company(company)
company_id = company_obj[0]['id']
locations = cwObj.get_sites(company_id)
context = {'locations': locations}
return render(request, 'website/new_opportunity_location.html', context)
I imagine you had something close to this? A Reference before assignment means your trying to access a variable that hasn't been set yet. So this probably means that line company_id = company_obj[0]['id']
returned none and then trying to use it in cwObj.get_sites(company_id)
caused a reference error
Upvotes: 1