Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sites.py 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. from functools import update_wrapper
  2. from weakref import WeakSet
  3. from django.apps import apps
  4. from django.contrib.admin import ModelAdmin, actions
  5. from django.contrib.auth import REDIRECT_FIELD_NAME
  6. from django.core.exceptions import ImproperlyConfigured
  7. from django.db.models.base import ModelBase
  8. from django.http import Http404, HttpResponseRedirect
  9. from django.template.response import TemplateResponse
  10. from django.urls import NoReverseMatch, reverse
  11. from django.utils.functional import LazyObject
  12. from django.utils.module_loading import import_string
  13. from django.utils.text import capfirst
  14. from django.utils.translation import gettext as _, gettext_lazy
  15. from django.views.decorators.cache import never_cache
  16. from django.views.decorators.csrf import csrf_protect
  17. from django.views.i18n import JavaScriptCatalog
  18. all_sites = WeakSet()
  19. class AlreadyRegistered(Exception):
  20. pass
  21. class NotRegistered(Exception):
  22. pass
  23. class AdminSite:
  24. """
  25. An AdminSite object encapsulates an instance of the Django admin application, ready
  26. to be hooked in to your URLconf. Models are registered with the AdminSite using the
  27. register() method, and the get_urls() method can then be used to access Django view
  28. functions that present a full admin interface for the collection of registered
  29. models.
  30. """
  31. # Text to put at the end of each page's <title>.
  32. site_title = gettext_lazy('Django site admin')
  33. # Text to put in each page's <h1>.
  34. site_header = gettext_lazy('Django administration')
  35. # Text to put at the top of the admin index page.
  36. index_title = gettext_lazy('Site administration')
  37. # URL for the "View site" link at the top of each admin page.
  38. site_url = '/'
  39. _empty_value_display = '-'
  40. login_form = None
  41. index_template = None
  42. app_index_template = None
  43. login_template = None
  44. logout_template = None
  45. password_change_template = None
  46. password_change_done_template = None
  47. def __init__(self, name='admin'):
  48. self._registry = {} # model_class class -> admin_class instance
  49. self.name = name
  50. self._actions = {'delete_selected': actions.delete_selected}
  51. self._global_actions = self._actions.copy()
  52. all_sites.add(self)
  53. def check(self, app_configs):
  54. """
  55. Run the system checks on all ModelAdmins, except if they aren't
  56. customized at all.
  57. """
  58. if app_configs is None:
  59. app_configs = apps.get_app_configs()
  60. app_configs = set(app_configs) # Speed up lookups below
  61. errors = []
  62. modeladmins = (o for o in self._registry.values() if o.__class__ is not ModelAdmin)
  63. for modeladmin in modeladmins:
  64. if modeladmin.model._meta.app_config in app_configs:
  65. errors.extend(modeladmin.check())
  66. return errors
  67. def register(self, model_or_iterable, admin_class=None, **options):
  68. """
  69. Register the given model(s) with the given admin class.
  70. The model(s) should be Model classes, not instances.
  71. If an admin class isn't given, use ModelAdmin (the default admin
  72. options). If keyword arguments are given -- e.g., list_display --
  73. apply them as options to the admin class.
  74. If a model is already registered, raise AlreadyRegistered.
  75. If a model is abstract, raise ImproperlyConfigured.
  76. """
  77. admin_class = admin_class or ModelAdmin
  78. if isinstance(model_or_iterable, ModelBase):
  79. model_or_iterable = [model_or_iterable]
  80. for model in model_or_iterable:
  81. if model._meta.abstract:
  82. raise ImproperlyConfigured(
  83. 'The model %s is abstract, so it cannot be registered with admin.' % model.__name__
  84. )
  85. if model in self._registry:
  86. raise AlreadyRegistered('The model %s is already registered' % model.__name__)
  87. # Ignore the registration if the model has been
  88. # swapped out.
  89. if not model._meta.swapped:
  90. # If we got **options then dynamically construct a subclass of
  91. # admin_class with those **options.
  92. if options:
  93. # For reasons I don't quite understand, without a __module__
  94. # the created class appears to "live" in the wrong place,
  95. # which causes issues later on.
  96. options['__module__'] = __name__
  97. admin_class = type("%sAdmin" % model.__name__, (admin_class,), options)
  98. # Instantiate the admin class to save in the registry
  99. self._registry[model] = admin_class(model, self)
  100. def unregister(self, model_or_iterable):
  101. """
  102. Unregister the given model(s).
  103. If a model isn't already registered, raise NotRegistered.
  104. """
  105. if isinstance(model_or_iterable, ModelBase):
  106. model_or_iterable = [model_or_iterable]
  107. for model in model_or_iterable:
  108. if model not in self._registry:
  109. raise NotRegistered('The model %s is not registered' % model.__name__)
  110. del self._registry[model]
  111. def is_registered(self, model):
  112. """
  113. Check if a model class is registered with this `AdminSite`.
  114. """
  115. return model in self._registry
  116. def add_action(self, action, name=None):
  117. """
  118. Register an action to be available globally.
  119. """
  120. name = name or action.__name__
  121. self._actions[name] = action
  122. self._global_actions[name] = action
  123. def disable_action(self, name):
  124. """
  125. Disable a globally-registered action. Raise KeyError for invalid names.
  126. """
  127. del self._actions[name]
  128. def get_action(self, name):
  129. """
  130. Explicitly get a registered global action whether it's enabled or
  131. not. Raise KeyError for invalid names.
  132. """
  133. return self._global_actions[name]
  134. @property
  135. def actions(self):
  136. """
  137. Get all the enabled actions as an iterable of (name, func).
  138. """
  139. return self._actions.items()
  140. @property
  141. def empty_value_display(self):
  142. return self._empty_value_display
  143. @empty_value_display.setter
  144. def empty_value_display(self, empty_value_display):
  145. self._empty_value_display = empty_value_display
  146. def has_permission(self, request):
  147. """
  148. Return True if the given HttpRequest has permission to view
  149. *at least one* page in the admin site.
  150. """
  151. return request.user.is_active and request.user.is_staff
  152. def admin_view(self, view, cacheable=False):
  153. """
  154. Decorator to create an admin view attached to this ``AdminSite``. This
  155. wraps the view and provides permission checking by calling
  156. ``self.has_permission``.
  157. You'll want to use this from within ``AdminSite.get_urls()``:
  158. class MyAdminSite(AdminSite):
  159. def get_urls(self):
  160. from django.urls import path
  161. urls = super().get_urls()
  162. urls += [
  163. path('my_view/', self.admin_view(some_view))
  164. ]
  165. return urls
  166. By default, admin_views are marked non-cacheable using the
  167. ``never_cache`` decorator. If the view can be safely cached, set
  168. cacheable=True.
  169. """
  170. def inner(request, *args, **kwargs):
  171. if not self.has_permission(request):
  172. if request.path == reverse('admin:logout', current_app=self.name):
  173. index_path = reverse('admin:index', current_app=self.name)
  174. return HttpResponseRedirect(index_path)
  175. # Inner import to prevent django.contrib.admin (app) from
  176. # importing django.contrib.auth.models.User (unrelated model).
  177. from django.contrib.auth.views import redirect_to_login
  178. return redirect_to_login(
  179. request.get_full_path(),
  180. reverse('admin:login', current_app=self.name)
  181. )
  182. return view(request, *args, **kwargs)
  183. if not cacheable:
  184. inner = never_cache(inner)
  185. # We add csrf_protect here so this function can be used as a utility
  186. # function for any view, without having to repeat 'csrf_protect'.
  187. if not getattr(view, 'csrf_exempt', False):
  188. inner = csrf_protect(inner)
  189. return update_wrapper(inner, view)
  190. def get_urls(self):
  191. from django.urls import include, path, re_path
  192. # Since this module gets imported in the application's root package,
  193. # it cannot import models from other applications at the module level,
  194. # and django.contrib.contenttypes.views imports ContentType.
  195. from django.contrib.contenttypes import views as contenttype_views
  196. def wrap(view, cacheable=False):
  197. def wrapper(*args, **kwargs):
  198. return self.admin_view(view, cacheable)(*args, **kwargs)
  199. wrapper.admin_site = self
  200. return update_wrapper(wrapper, view)
  201. # Admin-site-wide views.
  202. urlpatterns = [
  203. path('', wrap(self.index), name='index'),
  204. path('login/', self.login, name='login'),
  205. path('logout/', wrap(self.logout), name='logout'),
  206. path('password_change/', wrap(self.password_change, cacheable=True), name='password_change'),
  207. path(
  208. 'password_change/done/',
  209. wrap(self.password_change_done, cacheable=True),
  210. name='password_change_done',
  211. ),
  212. path('jsi18n/', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
  213. path(
  214. 'r/<int:content_type_id>/<path:object_id>/',
  215. wrap(contenttype_views.shortcut),
  216. name='view_on_site',
  217. ),
  218. ]
  219. # Add in each model's views, and create a list of valid URLS for the
  220. # app_index
  221. valid_app_labels = []
  222. for model, model_admin in self._registry.items():
  223. urlpatterns += [
  224. path('%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)),
  225. ]
  226. if model._meta.app_label not in valid_app_labels:
  227. valid_app_labels.append(model._meta.app_label)
  228. # If there were ModelAdmins registered, we should have a list of app
  229. # labels for which we need to allow access to the app_index view,
  230. if valid_app_labels:
  231. regex = r'^(?P<app_label>' + '|'.join(valid_app_labels) + ')/$'
  232. urlpatterns += [
  233. re_path(regex, wrap(self.app_index), name='app_list'),
  234. ]
  235. return urlpatterns
  236. @property
  237. def urls(self):
  238. return self.get_urls(), 'admin', self.name
  239. def each_context(self, request):
  240. """
  241. Return a dictionary of variables to put in the template context for
  242. *every* page in the admin site.
  243. For sites running on a subpath, use the SCRIPT_NAME value if site_url
  244. hasn't been customized.
  245. """
  246. script_name = request.META['SCRIPT_NAME']
  247. site_url = script_name if self.site_url == '/' and script_name else self.site_url
  248. return {
  249. 'site_title': self.site_title,
  250. 'site_header': self.site_header,
  251. 'site_url': site_url,
  252. 'has_permission': self.has_permission(request),
  253. 'available_apps': self.get_app_list(request),
  254. }
  255. def password_change(self, request, extra_context=None):
  256. """
  257. Handle the "change password" task -- both form display and validation.
  258. """
  259. from django.contrib.admin.forms import AdminPasswordChangeForm
  260. from django.contrib.auth.views import PasswordChangeView
  261. url = reverse('admin:password_change_done', current_app=self.name)
  262. defaults = {
  263. 'form_class': AdminPasswordChangeForm,
  264. 'success_url': url,
  265. 'extra_context': {**self.each_context(request), **(extra_context or {})},
  266. }
  267. if self.password_change_template is not None:
  268. defaults['template_name'] = self.password_change_template
  269. request.current_app = self.name
  270. return PasswordChangeView.as_view(**defaults)(request)
  271. def password_change_done(self, request, extra_context=None):
  272. """
  273. Display the "success" page after a password change.
  274. """
  275. from django.contrib.auth.views import PasswordChangeDoneView
  276. defaults = {
  277. 'extra_context': {**self.each_context(request), **(extra_context or {})},
  278. }
  279. if self.password_change_done_template is not None:
  280. defaults['template_name'] = self.password_change_done_template
  281. request.current_app = self.name
  282. return PasswordChangeDoneView.as_view(**defaults)(request)
  283. def i18n_javascript(self, request, extra_context=None):
  284. """
  285. Display the i18n JavaScript that the Django admin requires.
  286. `extra_context` is unused but present for consistency with the other
  287. admin views.
  288. """
  289. return JavaScriptCatalog.as_view(packages=['django.contrib.admin'])(request)
  290. @never_cache
  291. def logout(self, request, extra_context=None):
  292. """
  293. Log out the user for the given HttpRequest.
  294. This should *not* assume the user is already logged in.
  295. """
  296. from django.contrib.auth.views import LogoutView
  297. defaults = {
  298. 'extra_context': {
  299. **self.each_context(request),
  300. # Since the user isn't logged out at this point, the value of
  301. # has_permission must be overridden.
  302. 'has_permission': False,
  303. **(extra_context or {})
  304. },
  305. }
  306. if self.logout_template is not None:
  307. defaults['template_name'] = self.logout_template
  308. request.current_app = self.name
  309. return LogoutView.as_view(**defaults)(request)
  310. @never_cache
  311. def login(self, request, extra_context=None):
  312. """
  313. Display the login form for the given HttpRequest.
  314. """
  315. if request.method == 'GET' and self.has_permission(request):
  316. # Already logged-in, redirect to admin index
  317. index_path = reverse('admin:index', current_app=self.name)
  318. return HttpResponseRedirect(index_path)
  319. from django.contrib.auth.views import LoginView
  320. # Since this module gets imported in the application's root package,
  321. # it cannot import models from other applications at the module level,
  322. # and django.contrib.admin.forms eventually imports User.
  323. from django.contrib.admin.forms import AdminAuthenticationForm
  324. context = {
  325. **self.each_context(request),
  326. 'title': _('Log in'),
  327. 'app_path': request.get_full_path(),
  328. 'username': request.user.get_username(),
  329. }
  330. if (REDIRECT_FIELD_NAME not in request.GET and
  331. REDIRECT_FIELD_NAME not in request.POST):
  332. context[REDIRECT_FIELD_NAME] = reverse('admin:index', current_app=self.name)
  333. context.update(extra_context or {})
  334. defaults = {
  335. 'extra_context': context,
  336. 'authentication_form': self.login_form or AdminAuthenticationForm,
  337. 'template_name': self.login_template or 'admin/login.html',
  338. }
  339. request.current_app = self.name
  340. return LoginView.as_view(**defaults)(request)
  341. def _build_app_dict(self, request, label=None):
  342. """
  343. Build the app dictionary. The optional `label` parameter filters models
  344. of a specific app.
  345. """
  346. app_dict = {}
  347. if label:
  348. models = {
  349. m: m_a for m, m_a in self._registry.items()
  350. if m._meta.app_label == label
  351. }
  352. else:
  353. models = self._registry
  354. for model, model_admin in models.items():
  355. app_label = model._meta.app_label
  356. has_module_perms = model_admin.has_module_permission(request)
  357. if not has_module_perms:
  358. continue
  359. perms = model_admin.get_model_perms(request)
  360. # Check whether user has any perm for this module.
  361. # If so, add the module to the model_list.
  362. if True not in perms.values():
  363. continue
  364. info = (app_label, model._meta.model_name)
  365. model_dict = {
  366. 'name': capfirst(model._meta.verbose_name_plural),
  367. 'object_name': model._meta.object_name,
  368. 'perms': perms,
  369. }
  370. if perms.get('change') or perms.get('view'):
  371. model_dict['view_only'] = not perms.get('change')
  372. try:
  373. model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
  374. except NoReverseMatch:
  375. pass
  376. if perms.get('add'):
  377. try:
  378. model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name)
  379. except NoReverseMatch:
  380. pass
  381. if app_label in app_dict:
  382. app_dict[app_label]['models'].append(model_dict)
  383. else:
  384. app_dict[app_label] = {
  385. 'name': apps.get_app_config(app_label).verbose_name,
  386. 'app_label': app_label,
  387. 'app_url': reverse(
  388. 'admin:app_list',
  389. kwargs={'app_label': app_label},
  390. current_app=self.name,
  391. ),
  392. 'has_module_perms': has_module_perms,
  393. 'models': [model_dict],
  394. }
  395. if label:
  396. return app_dict.get(label)
  397. return app_dict
  398. def get_app_list(self, request):
  399. """
  400. Return a sorted list of all the installed apps that have been
  401. registered in this site.
  402. """
  403. app_dict = self._build_app_dict(request)
  404. # Sort the apps alphabetically.
  405. app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())
  406. # Sort the models alphabetically within each app.
  407. for app in app_list:
  408. app['models'].sort(key=lambda x: x['name'])
  409. return app_list
  410. @never_cache
  411. def index(self, request, extra_context=None):
  412. """
  413. Display the main admin index page, which lists all of the installed
  414. apps that have been registered in this site.
  415. """
  416. app_list = self.get_app_list(request)
  417. context = {
  418. **self.each_context(request),
  419. 'title': self.index_title,
  420. 'app_list': app_list,
  421. **(extra_context or {}),
  422. }
  423. request.current_app = self.name
  424. return TemplateResponse(request, self.index_template or 'admin/index.html', context)
  425. def app_index(self, request, app_label, extra_context=None):
  426. app_dict = self._build_app_dict(request, app_label)
  427. if not app_dict:
  428. raise Http404('The requested admin page does not exist.')
  429. # Sort the models alphabetically within each app.
  430. app_dict['models'].sort(key=lambda x: x['name'])
  431. app_name = apps.get_app_config(app_label).verbose_name
  432. context = {
  433. **self.each_context(request),
  434. 'title': _('%(app)s administration') % {'app': app_name},
  435. 'app_list': [app_dict],
  436. 'app_label': app_label,
  437. **(extra_context or {}),
  438. }
  439. request.current_app = self.name
  440. return TemplateResponse(request, self.app_index_template or [
  441. 'admin/%s/app_index.html' % app_label,
  442. 'admin/app_index.html'
  443. ], context)
  444. class DefaultAdminSite(LazyObject):
  445. def _setup(self):
  446. AdminSiteClass = import_string(apps.get_app_config('admin').default_site)
  447. self._wrapped = AdminSiteClass()
  448. # This global object represents the default admin site, for the common case.
  449. # You can provide your own AdminSite using the (Simple)AdminConfig.default_site
  450. # attribute. You can also instantiate AdminSite in your own code to create a
  451. # custom admin site.
  452. site = DefaultAdminSite()