├── .gitignore ├── DataBaseTenant ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py ├── README.md ├── Tenant ├── __init__.py ├── admin.py ├── apps.py ├── management │ └── commands │ │ └── my_custom_command.py ├── migrations │ └── __init__.py ├── models.py ├── tests.py ├── urls.py └── views.py ├── manage.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 105 | __pypackages__/ 106 | 107 | # Celery stuff 108 | celerybeat-schedule 109 | celerybeat.pid 110 | 111 | # SageMath parsed files 112 | *.sage.py 113 | 114 | # Environments 115 | .env 116 | .venv 117 | env/ 118 | venv/ 119 | ENV/ 120 | env.bak/ 121 | venv.bak/ 122 | 123 | # Spyder project settings 124 | .spyderproject 125 | .spyproject 126 | 127 | # Rope project settings 128 | .ropeproject 129 | 130 | # mkdocs documentation 131 | /site 132 | 133 | # mypy 134 | .mypy_cache/ 135 | .dmypy.json 136 | dmypy.json 137 | 138 | # Pyre type checker 139 | .pyre/ 140 | 141 | # pytype static type analyzer 142 | .pytype/ 143 | 144 | # Cython debug symbols 145 | cython_debug/ 146 | 147 | # PyCharm 148 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 149 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 150 | # and can be added to the global gitignore or merged into this file. For a more nuclear 151 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 152 | #.idea/ -------------------------------------------------------------------------------- /DataBaseTenant/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jitendra-meena/Django-Tenant/b4761ac7a9c0a44840b8d02faeabeb03d39c0601/DataBaseTenant/__init__.py -------------------------------------------------------------------------------- /DataBaseTenant/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for DataBaseTenant project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DataBaseTenant.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /DataBaseTenant/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for DataBaseTenant project. 3 | 4 | Generated by 'django-admin startproject' using Django 4.0.3. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/4.0/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | import django 15 | from django.utils.encoding import force_str 16 | django.utils.encoding.force_text = force_str 17 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 18 | BASE_DIR = Path(__file__).resolve().parent.parent 19 | 20 | 21 | # Quick-start development settings - unsuitable for production 22 | # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ 23 | 24 | # SECURITY WARNING: keep the secret key used in production secret! 25 | SECRET_KEY = 'django-insecure-dc%q(po_9d67qjrlu%g+4f-dkqrtji(z!*=-+0t$&7p7ltdtm8' 26 | 27 | # SECURITY WARNING: don't run with debug turned on in production! 28 | DEBUG = True 29 | 30 | ALLOWED_HOSTS = [] 31 | 32 | 33 | # Application definition 34 | 35 | INSTALLED_APPS = [ 36 | 'django.contrib.admin', 37 | 'django.contrib.auth', 38 | 'django.contrib.contenttypes', 39 | 'django.contrib.sessions', 40 | 'django.contrib.messages', 41 | 'django.contrib.staticfiles', 42 | 'Tenant' 43 | ] 44 | 45 | MIDDLEWARE = [ 46 | 'tenant_schemas.middleware.TenantMiddleware', 47 | 'django_tenants.middleware.main.TenantMainMiddleware', # Changes 48 | 'django.middleware.security.SecurityMiddleware', 49 | 'django.contrib.sessions.middleware.SessionMiddleware', 50 | 'django.middleware.common.CommonMiddleware', 51 | 'django.middleware.csrf.CsrfViewMiddleware', 52 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 53 | 'django.contrib.messages.middleware.MessageMiddleware', 54 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 55 | ] 56 | 57 | ROOT_URLCONF = 'DataBaseTenant.urls' 58 | 59 | # DataBase Routes 60 | DATABASE_ROUTERS = ( 61 | 'tenant_schemas.routers.TenantSyncRouter', 62 | ) 63 | 64 | TEMPLATES = [ 65 | { 66 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 67 | 'DIRS': [], 68 | 'APP_DIRS': True, 69 | 'OPTIONS': { 70 | 'context_processors': [ 71 | 'django.template.context_processors.debug', 72 | 'django.template.context_processors.request', 73 | 'django.contrib.auth.context_processors.auth', 74 | 'django.contrib.messages.context_processors.messages', 75 | ], 76 | }, 77 | }, 78 | ] 79 | 80 | WSGI_APPLICATION = 'DataBaseTenant.wsgi.application' 81 | 82 | 83 | # Database 84 | # https://docs.djangoproject.com/en/4.0/ref/settings/#databases 85 | 86 | # DATABASES = { 87 | # 'default': { 88 | # 'ENGINE': 'django.db.backends.sqlite3', 89 | # 'NAME': BASE_DIR / 'db.sqlite3', 90 | # } 91 | # } 92 | DATABASES = { 93 | 'default': { 94 | 'ENGINE': 'tenant_schemas.postgresql_backend', 95 | 'NAME': 'TenantDB', 96 | 'USER': 'postgres', 97 | 'PASSWORD':'postgres', 98 | 'HOST': 'localhost', 99 | 'PORT': '5432' 100 | } 101 | } 102 | 103 | DATABASE_ROUTERS = ( 104 | 'tenant_schemas.routers.TenantSyncRouter', 105 | ) 106 | 107 | #Tanent DataBase Register 108 | TENANT_MODEL = "Tanent.Client" # app.Model 109 | 110 | # Password validation 111 | # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators 112 | 113 | AUTH_PASSWORD_VALIDATORS = [ 114 | { 115 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 116 | }, 117 | { 118 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 119 | }, 120 | { 121 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 122 | }, 123 | { 124 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 125 | }, 126 | ] 127 | 128 | 129 | # Internationalization 130 | # https://docs.djangoproject.com/en/4.0/topics/i18n/ 131 | 132 | LANGUAGE_CODE = 'en-us' 133 | 134 | TIME_ZONE = 'UTC' 135 | 136 | USE_I18N = True 137 | 138 | USE_TZ = True 139 | 140 | 141 | # Static files (CSS, JavaScript, Images) 142 | # https://docs.djangoproject.com/en/4.0/howto/static-files/ 143 | 144 | STATIC_URL = 'static/' 145 | 146 | # Default primary key field type 147 | # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field 148 | 149 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 150 | -------------------------------------------------------------------------------- /DataBaseTenant/urls.py: -------------------------------------------------------------------------------- 1 | """DataBaseTenant URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/4.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path,include 18 | 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('',include('Tenant.urls')) 22 | ] 23 | -------------------------------------------------------------------------------- /DataBaseTenant/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for DataBaseTenant project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DataBaseTenant.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django-Tenant 2 | 3 | 4 | This application enables django powered websites to have multiple tenants via PostgreSQL schemas. A vital feature for every Software-as-a-Service (SaaS) website. 5 | 6 | 7 | # Setup & Documentation 8 | DATABASES = { 9 | 'default': { 10 | 'ENGINE': 'django_tenants.postgresql_backend', 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Tenant/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jitendra-meena/Django-Tenant/b4761ac7a9c0a44840b8d02faeabeb03d39c0601/Tenant/__init__.py -------------------------------------------------------------------------------- /Tenant/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /Tenant/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class TenantConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'Tenant' 7 | -------------------------------------------------------------------------------- /Tenant/management/commands/my_custom_command.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand 2 | from django.utils import timezone 3 | 4 | class Command(BaseCommand): 5 | help = 'Displays current time' 6 | 7 | def handle(self, *args, **kwargs): 8 | time = timezone.now().strftime('%X') 9 | self.stdout.write("It's now %s" % time) 10 | 11 | -------------------------------------------------------------------------------- /Tenant/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jitendra-meena/Django-Tenant/b4761ac7a9c0a44840b8d02faeabeb03d39c0601/Tenant/migrations/__init__.py -------------------------------------------------------------------------------- /Tenant/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.db import models 3 | from tenant_schemas.models import TenantMixin 4 | 5 | class Client(TenantMixin): 6 | name = models.CharField(max_length=100) 7 | paid_until = models.DateField() 8 | on_trial = models.BooleanField() 9 | created_on = models.DateField(auto_now_add=True) 10 | 11 | 12 | class Domain(TenantMixin): 13 | pass 14 | -------------------------------------------------------------------------------- /Tenant/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Tenant/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.urls import path 3 | 4 | urlpatterns = [ 5 | 6 | ] 7 | -------------------------------------------------------------------------------- /Tenant/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | # Create your views here. 4 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DataBaseTenant.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | asgiref==3.5.0 2 | backports.zoneinfo==0.2.1 3 | Django==4.0.3 4 | django-tenant-schemas==1.11.0 5 | django-tenants==3.4.2 6 | ordered-set==4.1.0 7 | psycopg2-binary==2.9.3 8 | six==1.16.0 9 | sqlparse==0.4.2 --------------------------------------------------------------------------------