SAFEER N
SAFEER N

Reputation: 1197

Django Global function and variable

I have one function in my view. I want to use this function in some other apps. Is there any way to declare this variable (shop_id) globally.

if "current_shop" in request.session:
    shop_id = request.session['current_shop']
elif request.user.is_superuser:
    shop_id = 1
else:
    shop_id = 2

Upvotes: 3

Views: 5287

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124388

Make it a function your views use; return the shop_id value from the function:

def get_shop_id(request):
    if "current_shop" in request.session:
        return request.session['current_shop']

    return 1 if request.user.is_superuser else 2

and in your views:

shop_id = get_shop_id(request)

If you put this in a separate module; say utils.py, you can import it with:

from projectname.utils import get_shop_id

or using a relative import:

from .utils import get_shop_id

provided utils.py lives in the same package as your views.

Upvotes: 11

Related Questions