django-multisite2 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. django_multisite2-2.0.0.dist-info/LICENSE +28 -0
  2. django_multisite2-2.0.0.dist-info/METADATA +246 -0
  3. django_multisite2-2.0.0.dist-info/RECORD +51 -0
  4. django_multisite2-2.0.0.dist-info/WHEEL +5 -0
  5. django_multisite2-2.0.0.dist-info/top_level.txt +2 -0
  6. multisite/__init__.py +1 -0
  7. multisite/admin/__init__.py +3 -0
  8. multisite/admin/alias_admin.py +58 -0
  9. multisite/admin/multisite_changelist.py +64 -0
  10. multisite/admin/multisite_model_admin.py +161 -0
  11. multisite/apps.py +29 -0
  12. multisite/exceptions.py +57 -0
  13. multisite/forms.py +22 -0
  14. multisite/hacks.py +163 -0
  15. multisite/management/__init__.py +0 -0
  16. multisite/management/commands/__init__.py +0 -0
  17. multisite/management/commands/update_public_suffix_list.py +33 -0
  18. multisite/middleware/__init__.py +4 -0
  19. multisite/middleware/cookie_domain_middleware.py +72 -0
  20. multisite/middleware/dynamic_site_middleware.py +198 -0
  21. multisite/migrations/0001_initial.py +71 -0
  22. multisite/migrations/0002_alter_alias_id_alter_alias_is_canonical.py +32 -0
  23. multisite/migrations/0003_alter_alias_options_alter_alias_unique_together_and_more.py +41 -0
  24. multisite/migrations/0004_alter_alias_managers.py +22 -0
  25. multisite/migrations/__init__.py +0 -0
  26. multisite/models/__init__.py +3 -0
  27. multisite/models/alias.py +110 -0
  28. multisite/models/managers.py +196 -0
  29. multisite/models/signals.py +36 -0
  30. multisite/models/validators.py +14 -0
  31. multisite/tests/__init__.py +0 -0
  32. multisite/tests/get_test_allowed_hosts.py +14 -0
  33. multisite/tests/get_test_http_response.py +13 -0
  34. multisite/tests/hosts.py +46 -0
  35. multisite/tests/test_settings.py +23 -0
  36. multisite/tests/tests/__init__.py +0 -0
  37. multisite/tests/tests/request_factory.py +12 -0
  38. multisite/tests/tests/test_alias.py +271 -0
  39. multisite/tests/tests/test_contrib_site.py +21 -0
  40. multisite/tests/tests/test_cookie_domain_middleware.py +196 -0
  41. multisite/tests/tests/test_dynamic_site_middleware.py +262 -0
  42. multisite/tests/tests/test_site_cache.py +127 -0
  43. multisite/tests/tests/test_site_domain.py +24 -0
  44. multisite/tests/tests/test_site_id.py +76 -0
  45. multisite/tests/tests/test_template_loader.py +49 -0
  46. multisite/threadlocals.py +136 -0
  47. multisite/utils.py +172 -0
  48. multisite_app/__init__.py +0 -0
  49. multisite_app/apps.py +6 -0
  50. multisite_app/urls.py +5 -0
  51. multisite_app/views.py +8 -0
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2023, Ecometrica
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,246 @@
1
+ Metadata-Version: 2.1
2
+ Name: django-multisite2
3
+ Version: 2.0.0
4
+ Summary: Serve multiple sites from a single Django application
5
+ Home-page: http://github.com/erikvw/django-multisite
6
+ Author: Leonid S Shestera
7
+ Author-email: leonid@shestera.ru
8
+ Maintainer: Ecometrica
9
+ Maintainer-email: dev@ecometrica.com
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Web Environment
12
+ Classifier: Framework :: Django
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: BSD License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Internet
20
+ Classifier: Topic :: Internet :: WWW/HTTP
21
+ Classifier: Topic :: Software Development :: Libraries
22
+ Classifier: Topic :: Utilities
23
+ Requires-Python: >=3.11
24
+ Description-Content-Type: text/x-rst
25
+ License-File: LICENSE
26
+ Requires-Dist: tldextract
27
+
28
+ |actions| |codecov| |downloads| |maintainability| |black|
29
+
30
+
31
+
32
+ README
33
+ ======
34
+
35
+ Python 3.11+ Django 4.2+
36
+
37
+ Older versions of Django are supported by the original `django-multisite`_ project.
38
+
39
+ .. _django-multisite: https://github.com/ecometrica/django-multisite
40
+
41
+
42
+ Installation
43
+ ============
44
+
45
+ Install with pip:
46
+
47
+ .. code-block::
48
+
49
+ pip install django-multisite2 (no release yet)
50
+
51
+
52
+ Replace your ``SITE_ID`` in ``settings.py`` to:
53
+
54
+ .. code-block::
55
+
56
+ from multisite import SiteID
57
+ SITE_ID = SiteID(default=1)
58
+
59
+
60
+ add to INSTALLED_APPS:
61
+
62
+ .. code-block::
63
+
64
+ INSTALLED_APPS = [
65
+ ...
66
+ 'django.contrib.sites',
67
+ 'multisite',
68
+ ...
69
+ ]
70
+
71
+
72
+ Edit settings.py MIDDLEWARE:
73
+
74
+ .. code-block::
75
+
76
+ MIDDLEWARE = (
77
+ ...
78
+ 'multisite.middleware.DynamicSiteMiddleware',
79
+ ...
80
+ )
81
+
82
+
83
+ Using a custom cache
84
+ --------------------
85
+ Append to settings.py, in order to use a custom cache that can be
86
+ safely cleared::
87
+
88
+ # The cache connection to use for django-multisite.
89
+ # Default: 'default'
90
+ CACHE_MULTISITE_ALIAS = 'multisite'
91
+
92
+ # The cache key prefix that django-multisite should use.
93
+ # If not set, defaults to the KEY_PREFIX used in the defined
94
+ # CACHE_MULTISITE_ALIAS or the default cache (empty string if not set)
95
+ CACHE_MULTISITE_KEY_PREFIX = ''
96
+
97
+ If you have set CACHE\_MULTISITE\_ALIAS to a custom value, *e.g.*
98
+ ``'multisite'``, add a separate backend to settings.py CACHES::
99
+
100
+ CACHES = {
101
+ 'default': {
102
+ ...
103
+ },
104
+ 'multisite': {
105
+ 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
106
+ 'TIMEOUT': 60 * 60 * 24, # 24 hours
107
+ ...
108
+ },
109
+ }
110
+
111
+
112
+ Domain fallbacks
113
+ ----------------
114
+
115
+ By default, if the domain name is unknown, multisite will respond with
116
+ an HTTP 404 Not Found error. To change this behaviour, add to
117
+ settings.py::
118
+
119
+ # The view function or class-based view that django-multisite will
120
+ # use when it cannot match the hostname with a Site. This can be
121
+ # the name of the function or the function itself.
122
+ # Default: None
123
+ MULTISITE_FALLBACK = 'django.views.generic.base.RedirectView
124
+
125
+ # Keyword arguments for the MULTISITE_FALLBACK view.
126
+ # Default: {}
127
+ MULTISITE_FALLBACK_KWARGS = {'url': 'http://example.com/',
128
+ 'permanent': False}
129
+
130
+ Templates
131
+ ---------
132
+ If required, create template subdirectories for domain level templates (in a
133
+ location specified in settings.TEMPLATES['DIRS'].
134
+
135
+ Multisite's template loader will look for templates in folders with the names of
136
+ domains, such as::
137
+
138
+ templates/example.com
139
+
140
+
141
+ The template loader will also look for templates in a folder specified by the
142
+ optional MULTISITE_DEFAULT_TEMPLATE_DIR setting, e.g.::
143
+
144
+ templates/multisite_templates
145
+
146
+
147
+ Cross-domain cookies
148
+ --------------------
149
+
150
+ In order to support `cross-domain cookies`_,
151
+ for purposes like single-sign-on,
152
+ prepend the following to the top of
153
+ settings.py MIDDLEWARE (MIDDLEWARE_CLASSES for Django < 1.10)::
154
+
155
+ MIDDLEWARE = (
156
+ 'multisite.middleware.CookieDomainMiddleware',
157
+ ...
158
+ )
159
+
160
+ CookieDomainMiddleware will consult the `Public Suffix List`_
161
+ for effective top-level domains.
162
+ It caches this file
163
+ in the system's default temporary directory
164
+ as ``effective_tld_names.dat``.
165
+ To change this in settings.py::
166
+
167
+ MULTISITE_PUBLIC_SUFFIX_LIST_CACHE = '/path/to/multisite_tld.dat'
168
+
169
+ By default,
170
+ any cookies without a domain set
171
+ will be reset to allow \*.domain.tld.
172
+ To change this in settings.py::
173
+
174
+ MULTISITE_COOKIE_DOMAIN_DEPTH = 1 # Allow only *.subdomain.domain.tld
175
+
176
+ In order to fetch a new version of the list,
177
+ run::
178
+
179
+ manage.py update_public_suffix_list
180
+
181
+ .. _cross-domain cookies: http://en.wikipedia.org/wiki/HTTP_cookie#Domain_and_Path
182
+ .. _Public Suffix List: http://publicsuffix.org/
183
+
184
+ Post-migrate signal: post_migrate_sync_alias
185
+ --------------------------------------------
186
+ The ``post-migrate`` signal ``post_migrate_sync_alias`` is registered in the ``apps.py``. ``post_migrate_sync_alias``
187
+ ensures the ``domain`` in multisite's ``Alias`` model is updated to match that of django's ``Site`` model. This signal must
188
+ run AFTER any ``post-migrate`` signals that manipulate Django's ``Site`` model. If you have an app that manipulates Django's
189
+ ``Site`` model, place it before ``multisite`` in `settings. INSTALLED_APPS`. If this is not possible, you may configure ``multisite``
190
+ to not connect the ``post-migrate`` signal in ``apps.py`` so that you can do it somewhere else in your code.
191
+
192
+ To configure `multisite` to not connect the `post-post_migrate_sync_alias` in the `apps.py`, update your settings::
193
+
194
+ MULTISITE_REGISTER_POST_MIGRATE_SYNC_ALIAS = False
195
+
196
+ With the `settings` attribute set to `False`, it is your responsibility to connect the signal in your code. Note that if you do not sync the `Alias` and `Site`
197
+ models after the `Site` model has changed, multisite may not recognize the domain and switch to the fallback view or
198
+ raise a `Http404` error.
199
+
200
+ Development Environments
201
+ ------------------------
202
+ Multisite returns a valid Alias when in "development mode" (defaulting to the
203
+ alias associated with the default SiteID.
204
+
205
+ Development mode is either:
206
+ - Running tests, i.e. manage.py test
207
+ - Running locally in settings.DEBUG = True, where the hostname is a top-level name, i.e. localhost
208
+
209
+ In order to have multisite use aliases in local environments, add entries to
210
+ your local etc/hosts file to match aliases in your applications. E.g. ::
211
+
212
+ 127.0.0.1 example.com
213
+ 127.0.0.1 examplealias.com
214
+
215
+ And access your application at example.com:8000 or examplealias.com:8000 instead of
216
+ the usual localhost:8000.
217
+
218
+ Tests
219
+ -----
220
+
221
+ To run the tests::
222
+
223
+ python runtests.py
224
+
225
+
226
+
227
+ .. |pypi| image:: https://img.shields.io/pypi/v/django-multisite2.svg
228
+ :target: https://pypi.python.org/pypi/django-multisite2
229
+
230
+ .. |actions| image:: https://github.com/erikvw/django-multisite2/actions/workflows/build.yml/badge.svg
231
+ :target: https://github.com/erikvw/django-multisite2/actions/workflows/build.yml
232
+
233
+ .. |codecov| image:: https://codecov.io/gh/erikvw/django-multisite2/branch/develop/graph/badge.svg
234
+ :target: https://codecov.io/gh/erikvw/django-multisite2
235
+
236
+ .. |downloads| image:: https://pepy.tech/badge/django-multisite2
237
+ :target: https://pepy.tech/project/django-multisite2
238
+
239
+ .. |maintainability| image:: https://api.codeclimate.com/v1/badges/4992e131641fc6929b1a/maintainability
240
+ :target: https://codeclimate.com/github/erikvw/django-multisite2/maintainability
241
+ :alt: Maintainability
242
+
243
+ .. |black| image:: https://img.shields.io/badge/code%20style-black-000000.svg
244
+ :target: https://github.com/ambv/black
245
+ :alt: Code Style
246
+
@@ -0,0 +1,51 @@
1
+ multisite/__init__.py,sha256=N5kF20yLIUBBJnzipFOibsoN3QTqP4qIIufdTmkw45U,45
2
+ multisite/apps.py,sha256=K69kWIqoWaZfbhlLVSxfYLQd-AhojiLxxXmjd26ljbo,975
3
+ multisite/exceptions.py,sha256=FwsrZfie71gUjiOlvDO9NYX8X58P1fTagfU-VBQ3qb8,1317
4
+ multisite/forms.py,sha256=LKojjbDvy3Lfu1-Tgjt4XKuJBYLkYOTBa4oRUJ12-dg,681
5
+ multisite/hacks.py,sha256=OZk7adtXOV37gzi8XETHMGr-cVVZkNbcWsAQrJT3h0E,5171
6
+ multisite/threadlocals.py,sha256=oyyTnTgJbx6fs2CoqsZi3eof_4pILtNJosXX2QQW1y4,4140
7
+ multisite/utils.py,sha256=dyvmg9USSMSZzuXJibsUPdLoBRZinV3uiTeI8H1iG5I,5544
8
+ multisite/admin/__init__.py,sha256=ySKx0DadaIOLct0obZeMG5ADQkMR6Scg2bMdXYTf9kc,145
9
+ multisite/admin/alias_admin.py,sha256=gL_1yrRN8otAijdTaK4WyJSeO40ZC3QD5PU-F818Fpk,1706
10
+ multisite/admin/multisite_changelist.py,sha256=PViIYIQ6GLL5D_HbDxTqUJt3TBImc5uYo-8MS_sIWFM,2376
11
+ multisite/admin/multisite_model_admin.py,sha256=2_p-M3jeTLmRlLR3D8KjQaBx_FB6CJWl_ZQdn0RT0bM,6414
12
+ multisite/management/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ multisite/management/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ multisite/management/commands/update_public_suffix_list.py,sha256=lu5zhgE2TgzsjpUT1AHPYV4UxSW68MsVcSmQCtx3-U0,974
15
+ multisite/middleware/__init__.py,sha256=77fFnj0H7FC-S81b62YfZMAfMPU4yKVp0JHmR0or6wk,183
16
+ multisite/middleware/cookie_domain_middleware.py,sha256=dan8R8A-lUJuO-9me86pJH1LJ4e9gxBS4yvzDXiYD1g,2358
17
+ multisite/middleware/dynamic_site_middleware.py,sha256=Y11ApIKxYHZJgxUVyvbcN5v9pHmBwwHgrO_fcL9ehWg,7515
18
+ multisite/migrations/0001_initial.py,sha256=TaASQ-9L_eIRlAa8dmsT6Z1nbBih2wah2abq4C39Yrc,2273
19
+ multisite/migrations/0002_alter_alias_id_alter_alias_is_canonical.py,sha256=V1Nc2K7nn8hwN8VdkgtUpwuU7z1lSajaPvhsuLLHvfk,911
20
+ multisite/migrations/0003_alter_alias_options_alter_alias_unique_together_and_more.py,sha256=SByQOusXLdf3xaeYIUuhJ5fkXlWqxAvS-WgqQL1n38s,1252
21
+ multisite/migrations/0004_alter_alias_managers.py,sha256=jZlYjSd-CkWGc3GE6hY6Kf8ZsCV6MQZkNbyFJ_gg_M4,649
22
+ multisite/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
+ multisite/models/__init__.py,sha256=bDgmZZANxdN9-x_VjeHKvp6xOsAjJ4Ex9iv4OIKzmQg,165
24
+ multisite/models/alias.py,sha256=xVWGKCxWBCuC52paOeS8QoZqy0PzYfLIKezH4cn3xng,3692
25
+ multisite/models/managers.py,sha256=dBhWrzl7U6XH26_br5BKPi8jxCCCaWQaQDWPXZPPSzo,6929
26
+ multisite/models/signals.py,sha256=LghEu50Vc2PlLBHecMoKO0qhJ62cetMk0RfdnZ3-G1U,1540
27
+ multisite/models/validators.py,sha256=Cq4fkmrQG4rlTDaWCjcmt_me6qRsPlxv3G2y5O79i1U,380
28
+ multisite/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
29
+ multisite/tests/get_test_allowed_hosts.py,sha256=lXcVJVbr37dmTKo3ajNYoqvDXw_G-JNWcP5iO-lmJgo,400
30
+ multisite/tests/get_test_http_response.py,sha256=qDFqBLULpFjZ5D_MeAOzzW29UD9QEEFiYpNGJocnGKk,329
31
+ multisite/tests/hosts.py,sha256=YXgD6VHu5SNGHVCkY8hQPy0YDSgE98rz5x12D5IVpWo,1212
32
+ multisite/tests/test_settings.py,sha256=PaMu9ZaySI8X0AQQxDCvaYIbTLCo8TRtVDkn9vwc3Q8,575
33
+ multisite/tests/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
34
+ multisite/tests/tests/request_factory.py,sha256=8pYWNc4ImtZU-GnMHnj2TzO0PByGrjDyYpZ3bBe8YfU,381
35
+ multisite/tests/tests/test_alias.py,sha256=qZ9l0noPaxxbyddPqxV8tcfeWSJHcBFxUDhCwsUxRqw,10544
36
+ multisite/tests/tests/test_contrib_site.py,sha256=jbVWfynr--_azY257ZMQWefukQF5RR0zJ-JgHOxgB28,638
37
+ multisite/tests/tests/test_cookie_domain_middleware.py,sha256=4fqABR6ZMApJ4sUdjK0Y3j8-E6smowURMogVHthWZW4,9193
38
+ multisite/tests/tests/test_dynamic_site_middleware.py,sha256=vweXWXP8vRJe5d_F4b2ujhvF6iX8IUs4qpcqvX-tOsU,10931
39
+ multisite/tests/tests/test_site_cache.py,sha256=0ImbJj7_cSftfbCOGvhllLjB3--QuQB3LtxtX2miOsM,5139
40
+ multisite/tests/tests/test_site_domain.py,sha256=5bdJSEbuzJSeVmoI92NGeHEFJgwCIfDwppJj_HRA25E,923
41
+ multisite/tests/tests/test_site_id.py,sha256=PS3FqC2scTExOqn-pxVXwKjwrfuu5I7CE4Y3r1zQp6g,2889
42
+ multisite/tests/tests/test_template_loader.py,sha256=ydlM3wTpUV1_r8__Su9kGacLYHLzHPY7JMjhKNb51BA,1798
43
+ multisite_app/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
44
+ multisite_app/apps.py,sha256=Wtzh0ZFzebAdpxwSfZIjwDoOV_QB_9HrYimscmtZDo4,149
45
+ multisite_app/urls.py,sha256=C3OZY9b3XjMuunawaMLVsRKRKHYFROZm94JVx1NFR6Q,129
46
+ multisite_app/views.py,sha256=zGs26VicVANJm3HGjZ9Z4TvrWSn2V-f-FXr2AwVQRzY,217
47
+ django_multisite2-2.0.0.dist-info/LICENSE,sha256=ZYRfLPXzj_EygRXJSr99HR6EQuo2UmYHjYjC9YECitE,1497
48
+ django_multisite2-2.0.0.dist-info/METADATA,sha256=9WQfQS8b3bTC1hESliEt2mKtGK9agL1q1PyhDXZvJwk,7622
49
+ django_multisite2-2.0.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
50
+ django_multisite2-2.0.0.dist-info/top_level.txt,sha256=7Kbmk1LiZaUMQBzaIITFXoAQKQLFaA0YaulQ7obUTMM,24
51
+ django_multisite2-2.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.43.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ multisite
2
+ multisite_app
multisite/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .threadlocals import SiteDomain, SiteID
@@ -0,0 +1,3 @@
1
+ from .alias_admin import AliasAdmin
2
+ from .multisite_changelist import MultisiteChangeList
3
+ from .multisite_model_admin import MultisiteModelAdmin
@@ -0,0 +1,58 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from django.contrib import admin
6
+ from django.contrib.sites.admin import SiteAdmin
7
+ from django.contrib.sites.models import Site
8
+ from django.db import models
9
+
10
+ from ..forms import SiteForm
11
+ from ..models import Alias
12
+
13
+ if TYPE_CHECKING:
14
+ from django.contrib.auth.models import User
15
+ from django.core.handlers.wsgi import WSGIRequest as BaseWSGIRequest
16
+ from django.db.models import QuerySet
17
+
18
+ class UserProfile(models.Model):
19
+ user = models.ForeignKey(User, on_delete=models.PROTECT)
20
+ sites = models.ManyToManyField(Site, blank=True)
21
+
22
+ class WSGIRequest(BaseWSGIRequest):
23
+ user: User
24
+
25
+
26
+ @admin.register(Alias)
27
+ class AliasAdmin(admin.ModelAdmin):
28
+ """Admin for Alias model."""
29
+
30
+ list_display = ("domain", "site", "is_canonical", "redirect_to_canonical")
31
+ list_filter = ("is_canonical", "redirect_to_canonical")
32
+ ordering = ("domain",)
33
+ raw_id_fields = ("site",)
34
+ readonly_fields = ("is_canonical",)
35
+ search_fields = ("domain",)
36
+
37
+
38
+ class AliasInline(admin.TabularInline):
39
+ """Inline for Alias model, showing non-canonical aliases."""
40
+
41
+ model = Alias
42
+ extra = 1
43
+ ordering = ("domain",)
44
+
45
+ def get_queryset(self, request: WSGIRequest) -> QuerySet[Alias]:
46
+ """Returns only non-canonical aliases."""
47
+ qs = self.model.aliases.get_queryset()
48
+ ordering = self.ordering or ()
49
+ if ordering:
50
+ qs = qs.order_by(*ordering)
51
+ return qs
52
+
53
+
54
+ # HACK: Monkeypatch AliasInline into SiteAdmin
55
+ SiteAdmin.inlines = type(SiteAdmin.inlines)([AliasInline]) + SiteAdmin.inlines
56
+
57
+ # HACK: Monkeypatch Alias validation into SiteForm
58
+ SiteAdmin.form = SiteForm
@@ -0,0 +1,64 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from django.contrib.admin.views.main import ChangeList
6
+ from django.contrib.sites.models import Site
7
+ from django.db import models
8
+
9
+ from ..utils import get_user_sites
10
+
11
+ __all__ = ["MultisiteChangeList"]
12
+
13
+ if TYPE_CHECKING:
14
+ from django.contrib.auth.models import User
15
+ from django.core.handlers.wsgi import WSGIRequest as BaseWSGIRequest
16
+
17
+ class UserProfile(models.Model):
18
+ user = models.ForeignKey(User, on_delete=models.PROTECT)
19
+ sites = models.ManyToManyField(Site, blank=True)
20
+
21
+ class WSGIRequest(BaseWSGIRequest):
22
+ user: User
23
+
24
+
25
+ class MultisiteChangeList(ChangeList):
26
+ """
27
+ A ChangeList like the built-in admin one, but it excludes site filters for
28
+ sites you're not associated with, unless you're a super-user.
29
+
30
+ At this point, it's probably fragile, given its reliance on Django
31
+ internals.
32
+ """
33
+
34
+ def get_filters(self, request: WSGIRequest, *args, **kwargs) -> tuple[list, bool]:
35
+ """
36
+ This might be considered a fragile function, since it relies on a
37
+ fair bit of Django's internals.
38
+ """
39
+ get_filters = super().get_filters
40
+ filter_specs, has_filter_specs = get_filters(request)
41
+ if request.user.is_superuser or not has_filter_specs:
42
+ return filter_specs, has_filter_specs
43
+ new_filter_specs = []
44
+ user_sites = frozenset(get_user_sites(request).values_list("pk", "domain"))
45
+ for filter_spec in filter_specs:
46
+ try:
47
+ try:
48
+ remote_model = filter_spec.field.remote_field.model
49
+ except AttributeError:
50
+ remote_model = filter_spec.field.related_model
51
+ except AttributeError:
52
+ new_filter_specs.append(filter_spec)
53
+ continue
54
+ if remote_model is not Site:
55
+ new_filter_specs.append(filter_spec)
56
+ continue
57
+ lookup_choices = frozenset(filter_spec.lookup_choices) & user_sites
58
+ if len(lookup_choices) > 1:
59
+ # put the choices back into the form they came in
60
+ filter_spec.lookup_choices = list(lookup_choices)
61
+ filter_spec.lookup_choices.sort()
62
+ new_filter_specs.append(filter_spec)
63
+
64
+ return new_filter_specs, bool(new_filter_specs)
@@ -0,0 +1,161 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from django.contrib import admin
6
+ from django.contrib.sites.models import Site
7
+ from django.db import models
8
+
9
+ from ..utils import get_user_sites
10
+ from .multisite_changelist import MultisiteChangeList
11
+
12
+ __all__ = ["MultisiteModelAdmin"]
13
+
14
+ if TYPE_CHECKING:
15
+ from django.contrib.auth.models import User
16
+ from django.core.handlers.wsgi import WSGIRequest as BaseWSGIRequest
17
+ from django.db.models import QuerySet
18
+
19
+ class UserProfile(models.Model):
20
+ user = models.ForeignKey(User, on_delete=models.PROTECT)
21
+ sites = models.ManyToManyField(Site, blank=True)
22
+
23
+ class WSGIRequest(BaseWSGIRequest):
24
+ user: User
25
+
26
+
27
+ class MultisiteModelAdmin(admin.ModelAdmin):
28
+ """
29
+ A very helpful ModelAdmin class for handling multi-site django
30
+ applications.
31
+ """
32
+
33
+ filter_sites_by_current_object = False
34
+
35
+ def __init__(self, model, admin_site):
36
+ self.object_sites: tuple | None = None
37
+ super().__init__(model, admin_site)
38
+
39
+ def get_queryset(self, request: WSGIRequest) -> QuerySet:
40
+ """
41
+ Filters lists of items to items belonging to sites assigned to the
42
+ current member.
43
+
44
+ Additionally, for cases where the field containing a reference
45
+ to 'site' or 'sites' isn't immediate -- one can supply the
46
+ ModelAdmin class with a list of fields to check the site of:
47
+
48
+ - multisite_filter_fields
49
+ A list of paths to a 'site' or 'sites' field on a related model to
50
+ filter the queryset on.
51
+
52
+ (As long as you're not a superuser)
53
+ """
54
+ qs = super().get_queryset(request)
55
+ if request.user.is_superuser:
56
+ return qs
57
+ user_sites = get_user_sites(request)
58
+ if hasattr(qs.model, "site"):
59
+ qs = qs.filter(site__in=user_sites)
60
+ elif hasattr(qs.model, "sites"):
61
+ qs = qs.filter(sites__in=user_sites)
62
+
63
+ if hasattr(self, "multisite_filter_fields"):
64
+ for field in self.multisite_filter_fields:
65
+ qkwargs = {"{field}__in".format(field=field): user_sites}
66
+ qs = qs.filter(**qkwargs)
67
+
68
+ return qs
69
+
70
+ def add_view(self, request: WSGIRequest, form_url: str = "", extra_context: dict = None):
71
+ if self.filter_sites_by_current_object:
72
+ if hasattr(self.model, "site") or hasattr(self.model, "sites"):
73
+ self.object_sites = tuple()
74
+ return super().add_view(request, form_url, extra_context)
75
+
76
+ def change_view(
77
+ self, request: WSGIRequest, object_id, form_url: str = "", extra_context: dict = None
78
+ ):
79
+ if self.filter_sites_by_current_object:
80
+ object_instance = self.get_object(request, object_id)
81
+ try:
82
+ self.object_sites = object_instance.sites.values_list("pk", flat=True)
83
+ except AttributeError:
84
+ try:
85
+ self.object_sites = (object_instance.site.pk,)
86
+ except AttributeError:
87
+ pass # assume the object doesn't belong to a site
88
+ return super().change_view(request, object_id, form_url, extra_context)
89
+
90
+ def handle_multisite_foreign_keys(self, db_field, request, **kwargs):
91
+ """
92
+ Filters the foreignkey queryset for fields referencing other models
93
+ to those models assigned to a site belonging to the current member
94
+ (if they aren't a superuser), and (optionally) belonging to the same
95
+ site as the current object.
96
+
97
+ Also prevents (non-super) users from assigning objects to sites that
98
+ they are not members of.
99
+
100
+ If the foreign key does not have a site/sites field directly, you can
101
+ specify a path to a site/sites field to filter on by setting the key:
102
+
103
+ - multisite_foreign_key_site_path
104
+
105
+ to a dictionary pointing specific foreign key field instances
106
+ from their model to the site field to filter on something
107
+ like:
108
+
109
+ multisite_indirect_foreign_key_path = {
110
+ 'plan_instance': 'plan__site'
111
+ }
112
+
113
+ for a field named 'plan_instance' referencing a model with a
114
+ foreign key named 'plan' having a foreign key to 'site'.
115
+
116
+ To filter the FK queryset to the same sites the current object belongs
117
+ to, simply set `filter_sites_by_current_object` to `True`.
118
+
119
+ Caveats:
120
+
121
+ 1) If you're adding an object that belongs to a site (or sites),
122
+ and you've set `self.limit_sites_by_current_object = True`,
123
+ then the FK fields to objects that also belong to a site won't show
124
+ any objects. This is due to filtering on an empty queryset.
125
+ """
126
+ user_sites = get_user_sites(request)
127
+ try:
128
+ remote_model = db_field.remote_field.model
129
+ except AttributeError:
130
+ remote_model = db_field.related_model
131
+ if hasattr(remote_model, "site"):
132
+ kwargs["queryset"] = remote_model._default_manager.filter(site__in=user_sites)
133
+ if hasattr(remote_model, "sites"):
134
+ kwargs["queryset"] = remote_model._default_manager.filter(sites__in=user_sites)
135
+ if db_field.name == "site" or db_field.name == "sites":
136
+ kwargs["queryset"] = user_sites
137
+ if (
138
+ hasattr(self, "multisite_indirect_foreign_key_path")
139
+ and db_field.name in self.multisite_indirect_foreign_key_path.keys()
140
+ ):
141
+ fkey = self.multisite_indirect_foreign_key_path[db_field.name]
142
+ kwargs["queryset"] = remote_model._default_manager.filter(**{fkey: user_sites})
143
+
144
+ return kwargs
145
+
146
+ def formfield_for_foreignkey(self, db_field, request, **kwargs):
147
+ kwargs = self.handle_multisite_foreign_keys(db_field, request, **kwargs)
148
+ return super().formfield_for_foreignkey(db_field, request, **kwargs)
149
+
150
+ def formfield_for_manytomany(self, db_field, request, **kwargs):
151
+ kwargs = self.handle_multisite_foreign_keys(db_field, request, **kwargs)
152
+ return super().formfield_for_manytomany(db_field, request, **kwargs)
153
+
154
+ def get_changelist(self, request, **kwargs):
155
+ """
156
+ Restrict the site filter (if there is one) to sites you are
157
+ associated with, or remove it entirely if you're just
158
+ associated with one site. Unless you're a super-user, of
159
+ course.
160
+ """
161
+ return MultisiteChangeList
multisite/apps.py ADDED
@@ -0,0 +1,29 @@
1
+ from django.apps import AppConfig as DjangoAppConfig
2
+ from django.conf import settings
3
+ from django.db.models.signals import post_migrate
4
+
5
+ from multisite.hacks import use_framework_for_site_cache
6
+ from multisite.utils import create_or_sync_canonical_from_all_sites
7
+
8
+
9
+ def post_migrate_sync_alias(apps=None, **kwargs):
10
+ """Syncs canonical Alias objects for all existing Site objects."""
11
+ create_or_sync_canonical_from_all_sites(apps)
12
+
13
+
14
+ class AppConfig(DjangoAppConfig):
15
+ name = "multisite"
16
+ verbose_name = "Multisite"
17
+ default_auto_field = "django.db.models.BigAutoField"
18
+
19
+ def import_models(self):
20
+ use_framework_for_site_cache()
21
+ super().import_models()
22
+
23
+ def ready(self):
24
+ if not getattr(settings, "MULTISITE_REGISTER_POST_MIGRATE_SYNC_ALIAS", True):
25
+ post_migrate.connect(
26
+ post_migrate_sync_alias,
27
+ sender=self,
28
+ dispatch_uid="multisite.post_migrate_sync_alias",
29
+ )