Skip to content
Snippets Groups Projects
Commit 3b6dbb89 authored by Nik | Klampfradler's avatar Nik | Klampfradler
Browse files

Ensure developers can get a school-related object outside a request.

parent c09c347f
No related branches found
No related tags found
No related merge requests found
from importlib import import_module
import pkgutil
from typing import Optional, Sequence
from warnings import warn
from django.apps import apps
from django.conf import settings
from django_global_request.middleware import get_request
......@@ -34,14 +38,28 @@ def get_current_school() -> Optional:
request = get_request()
if request:
if not hasattr(request, 'user'):
return None
if not hasattr(request.user, 'person'):
return None
# We are inside a web request, thus called from a public interface
if request.user.person:
if hasattr(request, 'user') and hasattr(request.user, 'person'):
# Use the same school as that of the logged-in user
return request.user.person.school
else:
# Set no school so no data is ever returned
# during an unauthenticated request
return None
else:
return None
# We are called from outside a request (probably shell),
# thus called from a private interface
School = apps.get_model('core.School')
if 'DEFAULT_SCHOOL' in settings:
# Use school defined in settings
return School.objects.get(pk=settings.DEFAULT_SCHOOL)
else:
# Use first school
warn('No school set, using first known school.', RuntimeWarning)
return School.objects.first()
# Raise an exception because not finding a school wreaks havoc
raise RuntimeError('No school set or found. Check your database.')
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment