Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Global function and variable

Tags:

python

django

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
like image 640
SAFEER N Avatar asked Jan 18 '26 14:01

SAFEER N


1 Answers

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.

like image 121
Martijn Pieters Avatar answered Jan 20 '26 04:01

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!