from .models import Theme, UserTheme def get_active_theme(request): objs_manager = Theme.objects user_theme_manager = UserTheme.objects objs_active_qs = objs_manager.filter(active=True) objs_active_ls = list(objs_active_qs) objs_active_count = len(objs_active_ls) if objs_active_count == 0: obj = objs_manager.first() if obj: obj.set_active() # else: # obj = objs_manager.create() elif objs_active_count == 1: obj = objs_active_ls[0] elif objs_active_count > 1: # for frame_record in inspect.stack(): # if frame_record[3]=='get_response': # request = frame_record[0].f_locals['request'] # user = request.user # break # else: # request = None user = request.user try: obj = user_theme_manager.filter(user=user, theme__active=True).first().theme except: objs_default_qs = objs_active_qs.filter(default=True) if len(objs_default_qs) == 0: obj = objs_active_qs.first() if obj: obj.set_default() else: obj = objs_default_qs.first() return { 'theme': obj, }