Compare commits

...
36 Commits
Author SHA1 Message Date
Ross 02a9118faf . 2025-12-08 09:29:30 +00:00
Ross 63c6a648d7 Add Loki, Promtail, and Grafana services for observability stack 2025-12-04 20:06:24 +00:00
Ross 517c30ba0e Enhance Docker setup with logging and monitoring features
- Added logging configuration to WSGI for persistent log collection.
- Updated Docker Compose files for local and development environments, including Redis, PostgreSQL, and Grafana services.
- Introduced Promtail configuration for log scraping and integration with Loki.
- Created application log directory in Dockerfile for log persistence.
2025-12-01 16:43:40 +00:00
Ross 590e0b76ed Add series images endpoint and template for HTMX integration 2025-12-01 14:50:11 +00:00
Ross e9a04e823c more docker improvements 2025-12-01 14:01:46 +00:00
Ross 9ed789ba90 more docker updates 2025-12-01 13:31:08 +00:00
Ross fd6e25d55e more ninja fixes 2025-12-01 13:31:02 +00:00
Ross f074e5b086 fix some ninja issuse 2025-12-01 13:30:43 +00:00
Ross 2157b6f781 some fixes? 2025-12-01 11:12:01 +00:00
Ross 359682a0cd start prod docker migration 2025-12-01 10:36:58 +00:00
Ross 78577076c1 Refactor discussion and report sections to use card layout for improved presentation and user interaction 2025-11-24 12:44:55 +00:00
Ross 3635275573 Enhance case view layout and styling for improved readability and user experience 2025-11-24 12:36:18 +00:00
Ross 0c412dfff6 Add prior cases information to collection case view template 2025-11-24 12:19:56 +00:00
Ross 3f00311136 Fix hx-post URL in prior card template for correct case number handling 2025-11-24 12:06:44 +00:00
Ross e8c35efd83 Refactor collection_case_questions function to use case_number instead of case_id for improved clarity and consistency in case retrieval 2025-11-24 12:02:43 +00:00
Ross 0badca4c4f Add default error value to context in collection_case_priors view to prevent variable resolution issues 2025-11-24 11:58:53 +00:00
Ross 25f4e478b3 Add edit permission check for collection case priors view 2025-11-24 11:53:50 +00:00
Ross 33cba3d005 Fix hx-post URL in prior card template for correct case number handling 2025-11-24 11:43:07 +00:00
Ross efca426359 Add case jump functionality with HTMX support and corresponding template 2025-11-24 11:40:52 +00:00
Ross f713632fdd Refactor Condition, Finding, and Structure tables: remove legacy primary field from displayed fields to streamline data representation. 2025-11-24 11:02:51 +00:00
Ross 785638ee23 Add cancel button to ConditionForm for easier navigation 2025-11-24 10:49:13 +00:00
Ross e8020c5d8f Update ConditionForm to use AJAX/autocomplete for canonical field selection 2025-11-24 10:42:38 +00:00
Ross 5ccf755e72 Refactor Condition model: remove legacy synonym and primary fields, introduce canonical field for aliasing. Update related documentation. 2025-11-24 10:31:13 +00:00
Ross 6308fbfcd7 Refactor Finding and Structure models: remove legacy primary and synonym fields, introduce canonical field for aliasing. Update filters and forms accordingly. 2025-11-24 10:18:26 +00:00
Ross 8a871d6332 Replace legacy primary filter with is_canonical and add synonym filter in ConditionFilter 2025-11-23 23:29:39 +00:00
Ross 6eeb4cbb1d Add canonical field and update synonym handling in Condition model
- Introduced a new `canonical` ForeignKey field in the Condition model to manage alias relationships.
- Enhanced synonym retrieval methods to prefer canonical names and handle aliases more effectively.
- Updated condition detail templates to reflect canonical status and improved synonym display.
- Implemented migration scripts to establish canonical relationships based on existing synonym links.
2025-11-20 22:48:03 +00:00
Ross 9d57d03cbb Refactor synonym management: extract synonyms list and add forms for adding synonyms with HTMX support 2025-11-20 21:59:50 +00:00
Ross 21de543313 Enhance ConditionForm: add Crispy Forms integration for consistent submit button rendering 2025-11-17 23:15:21 +00:00
Ross a12a9e38f3 Implement synonym management in condition detail: add forms for adding synonyms and handle POST requests for synonym creation. 2025-11-17 23:08:34 +00:00
Ross 81dc5bf48f Add forms and views for subspecialty, presentation, and pathological process management 2025-11-17 23:01:02 +00:00
Ross 4abb57900d Refactor categories dropdown: enhance layout with additional category options and staff creation links for improved navigation 2025-11-17 22:54:32 +00:00
Ross 08c9138cdb Refactor condition form: streamline JavaScript loading and enhance button layout for improved usability 2025-11-17 22:52:34 +00:00
Ross fb833a2b90 Refactor collection view: create a new template for collections with improved layout and staff action visibility 2025-11-17 22:47:15 +00:00
Ross 2f1e2f6abe Refactor collection_case_details: simplify case retrieval logic and improve parameter naming for clarity 2025-11-17 22:33:10 +00:00
Ross ffa717a9ef Refactor exam overview header: move author display earlier and remove duplicate block for improved clarity 2025-11-17 22:16:08 +00:00
Ross 2dd9f4af32 Refactor exam overview: enhance question display with improved layout and feedback visibility 2025-11-17 22:09:49 +00:00
59 changed files with 2836 additions and 599 deletions
+22
View File
@@ -0,0 +1,22 @@
# Django
DEBUG=1
SECRET_KEY=w(s0&(_eb058wvmg@44_repv8)r9@5p8fx*g_@c)1dm&d*ew^u
DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]
# External DB (you mentioned production uses an external DB)
DB_HOST=db-postgresql-lon1-05515-jan-22-backup-do-user-8165014-0.c.db.ondigitalocean.com
DB_PORT=25060
DB_NAME=testing
DB_USER=django
DB_PASSWORD=AVNS_NG_s4i7SMMobWLO
# Redis
REDIS_URL=redis://redis:6379/0
# Gunicorn tuning
GUNICORN_WORKERS=3
GUNICORN_LOGLEVEL=info
# Nginx host ports for local development (override prod defaults)
NGINX_HTTP_PORT=8000
NGINX_HTTPS_PORT=8443
+20
View File
@@ -0,0 +1,20 @@
# Copy this to .env.prod on the server and fill in production values (do NOT commit secrets).
# Django
SECRET_KEY=replace-me-with-a-secure-random-string
DEBUG=0
ALLOWED_HOSTS=example.com
# External DB (you mentioned production uses an external DB)
DATABASE_HOST=your.db.host
DATABASE_PORT=5432
DATABASE_NAME=rad
DATABASE_USER=django
DATABASE_PASSWORD=strong-db-password
# Redis
REDIS_URL=redis://redis:6379/0
# Gunicorn tuning
GUNICORN_WORKERS=3
GUNICORN_LOGLEVEL=info
+4
View File
@@ -12,3 +12,7 @@ venv
*.log
temp/
# Loki runtime data
/docker/loki-data/
/docker/loki-wal/
+15 -16
View File
@@ -19,51 +19,50 @@ from django.contrib.auth import get_user_model
router = Router()
class CidUserSchema(ModelSchema):
class Config:
class Meta:
model = CidUser
model_fields = ["cid", "name", "email"]
fields = ["cid", "name", "email"]
class UserUserSchema(ModelSchema):
class Config:
class Meta:
model = get_user_model()
model_fields = ["id", "email"]
fields = ["id", "email"]
class CidUserExamSchema(ModelSchema):
cid_user : CidUserSchema | None
user_user : UserUserSchema | None
class Config:
class Meta:
model = CidUserExam
model_fields = ["id"]
fields = ["id"]
class ExamStatusSchema(ModelSchema):
class Config:
class Meta:
model = ExamUserStatus
model_fields = ["id", "datetime", "status", "extra"]
fields = ["id", "datetime", "status", "extra"]
class ExamUserStatusSchema(ModelSchema):
#cid_user : CidUserSchema | None
#user_user : UserUserSchema | None
cid_user_exam : CidUserExamSchema | None
class Config:
class Meta:
model = ExamUserStatus
model_fields = ["id", "datetime", "status", "extra"]
fields = ["id", "datetime", "status", "extra"]
class QuestionSchema(ModelSchema):
class Config:
class Meta:
model = Question
#model_fields = ["question", "history", "feedback", "normal", "laterality"]
model_fields = "__all__"
fields = "__all__"
#model_exclude = ["answers"]
#exclude = ["answers"]
class ExamSchema(ModelSchema):
class Config:
class Meta:
model = Exam
model_fields = ["id", "name", "active", "publish_results"]
fields = ["id", "name", "active", "publish_results"]
@router.get('/')
def list_questions(request):
+4 -4
View File
@@ -32,9 +32,9 @@ router = Router()
class SeriesSchema(ModelSchema):
case_id: List[int] = []
class Config:
class Meta:
model = Series
model_fields = [
fields = [
"id",
"modality",
"examination",
@@ -48,9 +48,9 @@ class SeriesSchema(ModelSchema):
class CaseSchema(ModelSchema):
class Config:
class Meta:
model = Case
model_fields = ["id", "title"]
fields = ["id", "title"]
@router.post("/upload_dicom", auth=django_auth)
+60 -5
View File
@@ -164,13 +164,16 @@ class SeriesFilter(django_filters.FilterSet):
class ConditionFilter(django_filters.FilterSet):
# Replace legacy `primary` filter with `is_canonical` and provide a
# `synonym` filter which will filter by the canonical group of the
# selected condition.
is_canonical = django_filters.BooleanFilter(method="filter_is_canonical", label="Canonical")
synonym = django_filters.ModelChoiceFilter(queryset=Condition.objects.all(), method="filter_synonym", label="Synonym group")
class Meta:
model = Condition
fields = {
"name": ["icontains"],
"primary": ["exact"],
"synonym": ["exact"],
#"parent": ["exact"],
"subspecialty": ["exact"],
"rcr_curriculum": ["exact"],
}
@@ -189,11 +192,32 @@ class ConditionFilter(django_filters.FilterSet):
)
pass
def filter_is_canonical(self, queryset, name, value):
if value in (True, "True", "true", 1, "1"):
return queryset.filter(canonical__isnull=True)
if value in (False, "False", "false", 0, "0"):
return queryset.filter(canonical__isnull=False)
return queryset
def filter_synonym(self, queryset, name, value):
# value is a Condition instance selected in the filter. Return all
# Conditions that belong to the same canonical group as `value`.
if not value:
return queryset
master = value.canonical if value.canonical else value
return queryset.filter(Q(canonical=master) | Q(pk=master.pk))
class FindingFilter(django_filters.FilterSet):
# Replace legacy `primary`/`synonym` with canonical-based filters
is_canonical = django_filters.BooleanFilter(method="filter_is_canonical", label="Canonical")
synonym = django_filters.ModelChoiceFilter(queryset=Finding.objects.all(), method="filter_synonym", label="Synonym group")
class Meta:
model = Finding
fields = ("name", "primary", "synonym")
fields = {
"name": ["icontains"],
}
def __init__(
self,
@@ -209,11 +233,29 @@ class FindingFilter(django_filters.FilterSet):
)
pass
def filter_is_canonical(self, queryset, name, value):
if value in (True, "True", "true", 1, "1"):
return queryset.filter(canonical__isnull=True)
if value in (False, "False", "false", 0, "0"):
return queryset.filter(canonical__isnull=False)
return queryset
def filter_synonym(self, queryset, name, value):
# value is a Finding instance selected in the filter. Return all
# Findings that belong to the same canonical group as `value`.
if not value:
return queryset
master = value.canonical if value.canonical else value
return queryset.filter(Q(canonical=master) | Q(pk=master.pk))
class StructureFilter(django_filters.FilterSet):
is_canonical = django_filters.BooleanFilter(method="filter_is_canonical", label="Canonical")
synonym = django_filters.ModelChoiceFilter(queryset=Structure.objects.all(), method="filter_synonym", label="Synonym group")
class Meta:
model = Structure
fields = {"name": ["icontains"], "primary": ["exact"], "synonym": ["exact"]}
fields = {"name": ["icontains"]}
def __init__(
self,
@@ -229,6 +271,19 @@ class StructureFilter(django_filters.FilterSet):
)
pass
def filter_is_canonical(self, queryset, name, value):
if value in (True, "True", "true", 1, "1"):
return queryset.filter(canonical__isnull=True)
if value in (False, "False", "false", 0, "0"):
return queryset.filter(canonical__isnull=False)
return queryset
def filter_synonym(self, queryset, name, value):
if not value:
return queryset
master = value.canonical if value.canonical else value
return queryset.filter(Q(canonical=master) | Q(pk=master.pk))
class PresentationFilter(django_filters.FilterSet):
class Meta:
+86 -9
View File
@@ -40,6 +40,8 @@ from atlas.models import (
Condition,
Structure,
Subspecialty,
Presentation,
PathologicalProcess,
UncategorisedDicom,
UserReportAnswer,
CaseDisplaySet,
@@ -54,7 +56,8 @@ from generic.models import Examination # , Sign
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.forms.widgets import RadioSelect, TextInput, Textarea, Select
from crispy_forms.layout import Submit, Layout, Fieldset, Field, Div, HTML
from crispy_forms.layout import Submit, Layout, Fieldset, Field, Div, HTML, Button
from django.urls import reverse
from crispy_forms.bootstrap import Accordion, AccordionGroup
from tinymce.widgets import TinyMCE
@@ -116,11 +119,10 @@ class ConditionForm(ModelForm):
class Meta:
model = Condition
exclude = ["rcr_curriculum"]
widgets = {
"synonym": autocomplete.ModelSelect2Multiple(
url="atlas:condition-autocomplete"
),
# Use an AJAX/autocomplete single-select for canonical so users
# can search for existing canonical Conditions by name.
"canonical": autocomplete.ModelSelect2(url="atlas:condition-autocomplete"),
"parent": autocomplete.ModelSelect2Multiple(
url="atlas:condition-autocomplete"
),
@@ -129,6 +131,32 @@ class ConditionForm(ModelForm):
),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Crispy helper to render a submit button consistently
try:
self.helper = FormHelper()
self.helper.form_method = "post"
self.helper.form_tag = True
# Primary submit
self.helper.add_input(Submit("submit", "Submit"))
# Cancel as a button that redirects back to the condition list
try:
cancel_url = reverse("atlas:condition_view")
except Exception:
cancel_url = "#"
self.helper.add_input(
Button(
"cancel",
"Cancel",
css_class="btn btn-secondary ms-2",
onclick=f"window.location='{cancel_url}'",
)
)
except Exception:
# If crispy not available or something goes wrong, don't break form
pass
class CaseCollectionForm(ModelForm):
class Meta:
@@ -313,9 +341,10 @@ class FindingForm(ModelForm):
class Meta:
model = Finding
exclude = []
# Use the canonical FK in forms (if users want to mark this Finding
# as an alias of another). The old `synonym` M2M has been removed.
widgets = {
"synonym": autocomplete.ModelSelect2Multiple(
"canonical": autocomplete.ModelSelect2(
url="atlas:finding-autocomplete"
),
}
@@ -325,14 +354,31 @@ class StructureForm(ModelForm):
class Meta:
model = Structure
exclude = []
widgets = {
"synonym": autocomplete.ModelSelect2Multiple(
"canonical": autocomplete.ModelSelect2(
url="atlas:structure-autocomplete"
),
}
class SubspecialtyForm(ModelForm):
class Meta:
model = Subspecialty
exclude = []
class PresentationForm(ModelForm):
class Meta:
model = Presentation
exclude = []
class PathologicalProcessForm(ModelForm):
class Meta:
model = PathologicalProcess
exclude = []
class SeriesFindingForm(ModelForm):
class Meta:
model = SeriesFinding
@@ -1013,6 +1059,37 @@ class ConditionAutocomplete(ModelAutocomplete):
model = Condition
search_attrs = ["name"]
@classmethod
def get_items_from_keys(cls, keys, context_obj=None):
"""Return items for given keys, ignoring empty strings.
The autocomplete frontend sometimes sends empty string keys which
causes the ORM to raise ValueError when filtering numeric PK fields.
Filter out falsy/blank keys before querying. If no valid keys remain
return an empty queryset.
"""
# normalize and remove empty/blank values
clean_keys = [k for k in keys if k is not None and str(k).strip() != ""]
if not clean_keys:
return cls.model.objects.none()
# try to convert numeric keys to ints where possible
parsed_keys = []
for k in clean_keys:
try:
parsed_keys.append(int(k))
except Exception:
parsed_keys.append(k)
qs = cls.model.objects.filter(pk__in=parsed_keys)
# Return a list of dicts matching the autocomplete core expectations
# (items subscriptable by keys like 'key' / 'label').
return [
{"key": obj.pk, "label": getattr(obj, "name", str(obj)), "value": str(obj)}
for obj in qs
]
class ConditionAutocompleteForm(Form):
condition = ModelChoiceField(
+69
View File
@@ -0,0 +1,69 @@
from django.db import migrations, models
def forwards(apps, schema_editor):
Condition = apps.get_model("atlas", "Condition")
# Build connected components using existing M2M 'synonym' links
visited = set()
for cond in Condition.objects.all():
if cond.pk in visited:
continue
# BFS/DFS to collect component
stack = [cond]
comp = []
while stack:
c = stack.pop()
if c.pk in visited:
continue
visited.add(c.pk)
comp.append(c)
# access existing M2M relations
for s in c.synonym.all():
if s.pk not in visited:
stack.append(s)
# choose canonical: prefer primary==True else lowest pk
canon = None
for c in comp:
if getattr(c, "primary", False):
canon = c
break
if not canon:
canon = min(comp, key=lambda x: x.pk)
# set canonical for all non-canonical members
for c in comp:
if c.pk != canon.pk:
c.canonical_id = canon.pk
c.save()
def backwards(apps, schema_editor):
Condition = apps.get_model("atlas", "Condition")
for c in Condition.objects.all():
if c.canonical_id:
c.canonical_id = None
c.save()
class Migration(migrations.Migration):
dependencies = [
("atlas", "0085_rename_case_detail_caseprior_casedetail_and_more"),
]
operations = [
migrations.AddField(
model_name="condition",
name="canonical",
field=models.ForeignKey(
related_name="aliases",
null=True,
on_delete=models.SET_NULL,
to="atlas.condition",
blank=True,
),
),
migrations.RunPython(forwards, backwards),
]
@@ -0,0 +1,19 @@
# Generated by Django 5.2.7 on 2025-11-20 22:35
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('atlas', '0086_add_canonical'),
]
operations = [
migrations.AlterField(
model_name='condition',
name='canonical',
field=models.ForeignKey(blank=True, help_text='If set, this Condition is an alias and points to the canonical Condition.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='aliases', to='atlas.condition'),
),
]
@@ -0,0 +1,40 @@
# Generated by Django 5.2.7 on 2025-11-24 10:17
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('atlas', '0087_alter_condition_canonical'),
]
operations = [
migrations.RemoveField(
model_name='finding',
name='primary',
),
migrations.RemoveField(
model_name='finding',
name='synonym',
),
migrations.RemoveField(
model_name='structure',
name='primary',
),
migrations.RemoveField(
model_name='structure',
name='synonym',
),
migrations.AddField(
model_name='finding',
name='canonical',
field=models.ForeignKey(blank=True, help_text='If set, this Finding is an alias and points to the canonical Finding.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='aliases', to='atlas.finding'),
),
migrations.AddField(
model_name='structure',
name='canonical',
field=models.ForeignKey(blank=True, help_text='If set, this Structure is an alias and points to the canonical Structure.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='aliases', to='atlas.structure'),
),
]
@@ -0,0 +1,21 @@
# Generated by Django 5.2.7 on 2025-11-24 10:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('atlas', '0088_remove_finding_primary_remove_finding_synonym_and_more'),
]
operations = [
migrations.RemoveField(
model_name='condition',
name='primary',
),
migrations.RemoveField(
model_name='condition',
name='synonym',
),
]
+173 -29
View File
@@ -110,36 +110,121 @@ class SynMixin(object):
# abstract = True
def __str__(self) -> str:
if self.primary:
# Determine whether this record should be displayed as the
# canonical/primary entry. Prefer the new canonical FK pattern
# (`canonical is None` means this object is the master). Fallback
# to legacy `primary` boolean when present.
# If the model supports canonical FK, consider canonical==None as
# the primary/master entry. For models without canonical (legacy
# edge-cases), treat the instance as primary by default.
if hasattr(self, "canonical"):
try:
if self.canonical is None or self.canonical == self:
return self.name
else:
return f"{self.name} [syn]"
except Exception:
# defensive fallback
return f"{self.name} [syn]"
def get_old_str(self) -> str:
if self.primary:
if self.synonym.count() == 0:
# No canonical support: assume primary
return self.name
def get_old_str(self) -> str:
# Prefer using a model-specific get_synonyms (e.g. Condition.get_synonyms)
try:
syns = self.get_synonyms()
except Exception:
syns = None
# If the model supports canonical, only canonical==None entries
# should be rendered as the primary name. For models without
# canonical, treat instance as primary.
if hasattr(self, "canonical"):
try:
is_primary = self.canonical is None or self.canonical == self
except Exception:
is_primary = False
else:
synonyms = ",".join([i.name for i in self.synonym.all()])
is_primary = True
if is_primary:
if syns is None:
synonyms_field = getattr(self, "synonym", None)
if synonyms_field is None or (hasattr(synonyms_field, "count") and synonyms_field.count() == 0):
return self.name
synonyms = ",".join([i.name for i in synonyms_field.all()])
return f"{self.name} ({synonyms})"
else:
if not syns:
return self.name
synonyms = ",".join([i.name for i in syns])
return f"{self.name} ({synonyms})"
return f"{self.name} [syn]"
def get_synonym(self):
if self.primary:
# Return a readable synonym string. For models that implement
# get_synonyms (Condition with canonical/aliases), use that.
try:
syns = self.get_synonyms()
except Exception:
syns = None
# If canonical is present and this instance is the master, mark Primary
if hasattr(self, "canonical"):
try:
if self.canonical is None or self.canonical == self:
return "[Primary]"
else:
s = self.synonym.filter(primary=True).values_list("name", flat=True)
except Exception:
pass
if syns is None:
synonyms_field = getattr(self, "synonym", None)
if synonyms_field is None:
return ""
# If the old M2M exists, prefer those marked primary if such a
# attribute exists on the related objects.
try:
# Select all synonym names; legacy `primary` flag removed.
s = synonyms_field.values_list("name", flat=True)
except Exception:
s = []
return ", ".join(s)
# prefer primary names among synonyms if present
primary_names = []
for i in syns:
# Prefer items that are canonical/master in the group
if getattr(i, "canonical", None) is None:
primary_names.append(i.name)
if primary_names:
return ", ".join(primary_names)
return ", ".join([i.name for i in syns])
def get_synonym_link(self):
if self.primary:
try:
syns = self.get_synonyms()
except Exception:
syns = None
# Prefer canonical/master check
if hasattr(self, "canonical"):
try:
if self.canonical is None or self.canonical == self:
return "[Primary]"
else:
syns = self.synonym.filter(primary=True)
return ", ".join(
[f"<a href='{s.get_absolute_url()}'>{s.name}</a>" for s in syns]
)
except Exception:
pass
if syns is None:
# fall back to all M2M synonyms (not just primary) for models
# that still use the old synonym field (e.g. Finding, Structure)
synonyms_field = getattr(self, "synonym", None)
if synonyms_field is None:
return ""
syns_qs = synonyms_field.all()
items = [f"<a href='{s.get_absolute_url()}'>{s.name}</a>" for s in syns_qs]
return ", ".join(items)
# render links for synonyms/canonical group
items = [f"<a href='{s.get_absolute_url()}'>{s.name}</a>" for s in syns]
return ", ".join(items)
def get_link(self):
return format_html("<a href='{}'>{}</a>", self.get_absolute_url(), self.name)
@@ -147,21 +232,49 @@ class SynMixin(object):
class Finding(SynMixin, models.Model):
name = models.CharField(max_length=255, unique=True)
synonym = models.ManyToManyField("self", blank=True)
primary = models.BooleanField(default="True")
# New canonical/alias field: if set, this Finding is an alias and points
# to the canonical/master Finding. We remove the old M2M `synonym` and
# `primary` boolean in favour of this single canonical FK.
canonical = models.ForeignKey(
"self",
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name="aliases",
help_text="If set, this Finding is an alias and points to the canonical Finding.",
)
def get_absolute_url(self):
return reverse("atlas:finding_detail", kwargs={"pk": self.pk})
@property
def canonical_finding(self):
return self.canonical if self.canonical else self
def get_synonyms(self):
"""Return other Findings that are aliases/synonyms for this concept.
Behaviour mirrors Condition.get_synonyms: if this Finding is an alias
(has canonical set) return the canonical and other aliases (excluding
self). If this Finding is canonical, return all aliases (excluding
self).
"""
master = self.canonical_finding
qs = Finding.objects.filter(models.Q(canonical=master) | models.Q(pk=master.pk)).exclude(pk=self.pk)
return qs
class Condition(SynMixin, models.Model):
name = models.CharField(max_length=255, unique=True)
synonym = models.ManyToManyField(
# New canonical/alias field (Option B): if set, this Condition is an alias
# and points to the canonical/master Condition.
canonical = models.ForeignKey(
"self",
null=True,
blank=True,
help_text="Use if a direct synonym for the condition exists, e.g. 'Wegener granulomatosis' and 'Granulomatosis with Polyangitis'.",
on_delete=models.SET_NULL,
related_name="aliases",
help_text="If set, this Condition is an alias and points to the canonical Condition.",
)
parent = models.ManyToManyField(
"self",
@@ -172,10 +285,10 @@ class Condition(SynMixin, models.Model):
help_text="Use if the condition could be considered a subset of another, e.g. 'Alzheimer disease' and 'Dementia'.",
)
primary = models.BooleanField(
default="True",
help_text="Sets if this should be the canonical item, all other synonyms will then redirect to this by default.",
)
# Legacy fields `synonym` (M2M) and `primary` (boolean) have been removed.
# Canonical/aliases are represented by the `canonical` ForeignKey and
# the reverse `aliases` related_name. Use `get_synonyms()` /
# `canonical_condition` to access canonical groups.
subspecialty = models.ManyToManyField(
"subspecialty",
@@ -198,6 +311,23 @@ class Condition(SynMixin, models.Model):
def get_absolute_url(self):
return reverse("atlas:condition_detail", kwargs={"pk": self.pk})
@property
def canonical_condition(self):
"""Return the canonical/master condition for this Condition (self if none)."""
return self.canonical if self.canonical else self
def get_synonyms(self):
"""Return other Conditions that are synonyms/aliases for this concept.
Behaviour:
- If this Condition is an alias (canonical set), return the canonical and
any other aliases (excluding self).
- If this Condition is canonical, return all aliases (and exclude self).
"""
master = self.canonical_condition
qs = Condition.objects.filter(models.Q(canonical=master) | models.Q(pk=master.pk)).exclude(pk=self.pk)
return qs
def get_children(self):
return self.child.all()
@@ -276,14 +406,28 @@ class Differential(models.Model):
class Structure(SynMixin, models.Model):
name = models.CharField(max_length=255, unique=True)
synonym = models.ManyToManyField("self", blank=True)
primary = models.BooleanField(default="True")
# Migrate to canonical/aliases model like Condition and Finding
canonical = models.ForeignKey(
"self",
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name="aliases",
help_text="If set, this Structure is an alias and points to the canonical Structure.",
)
def get_absolute_url(self):
return reverse("atlas:structure_detail", kwargs={"pk": self.pk})
@property
def canonical_structure(self):
return self.canonical if self.canonical else self
def get_synonyms(self):
master = self.canonical_structure
qs = Structure.objects.filter(models.Q(canonical=master) | models.Q(pk=master.pk)).exclude(pk=self.pk)
return qs
@reversion.register
class Case(models.Model, AuthorMixin, QuestionMixin):
+3 -3
View File
@@ -276,7 +276,7 @@ class ConditionTable(SelectionTable):
class Meta(SelectionTable.Meta):
model = Condition
template_name = "django_tables2/bootstrap4.html"
fields = ("primary", "subspecialty", "rcr_curriculum_map", "rcr_curriculum")
fields = ("subspecialty", "rcr_curriculum_map", "rcr_curriculum")
sequence = ("name",)
@@ -312,7 +312,7 @@ class FindingTable(SelectionTable):
class Meta(SelectionTable.Meta):
model = Finding
template_name = "django_tables2/bootstrap4.html"
fields = ("name", "primary")
fields = ("name",)
sequence = ("name",)
@@ -339,7 +339,7 @@ class StructureTable(SelectionTable):
class Meta(SelectionTable.Meta):
model = Structure
template_name = "django_tables2/bootstrap4.html"
fields = ("name", "primary")
fields = ("name",)
sequence = ("name",)
+26 -2
View File
@@ -66,8 +66,32 @@
</li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'atlas:categories_list' %}"><i class="bi bi-tags me-1" aria-hidden="true"></i>Categories</a>
<li class="nav-item dropdown">
<a class="nav-link d-inline" href="{% url 'atlas:categories_list' %}"><i class="bi bi-tags me-1" aria-hidden="true"></i>Categories</a>
<a class="nav-link d-inline dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false">
<span class="visually-hidden">Toggle Dropdown</span>
</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="{% url 'atlas:categories_list' %}"><i class="bi bi-list-ul me-1" aria-hidden="true"></i>All categories</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{% url 'atlas:condition_view' %}">Conditions</a></li>
<li><a class="dropdown-item" href="{% url 'atlas:finding_view' %}">Findings</a></li>
<li><a class="dropdown-item" href="{% url 'atlas:structure_view' %}">Structures</a></li>
<li><a class="dropdown-item" href="{% url 'atlas:subspecialty_view' %}">Subspecialties</a></li>
<li><a class="dropdown-item" href="{% url 'atlas:presentation_view' %}">Presentations</a></li>
<li><a class="dropdown-item" href="{% url 'atlas:pathological_process_view' %}">Pathological process</a></li>
{% if request.user.is_staff %}
<li><hr class="dropdown-divider"></li>
<li class="dropdown-item-text small text-muted px-3">Create</li>
<li><a class="dropdown-item" href="{% url 'atlas:condition_create' %}">New condition</a></li>
<li><a class="dropdown-item" href="{% url 'atlas:finding_create' %}">New finding</a></li>
<li><a class="dropdown-item" href="{% url 'atlas:structure_create' %}">New structure</a></li>
<li><a class="dropdown-item" href="{% url 'atlas:subspecialty_create' %}">New subspecialty</a></li>
<li><a class="dropdown-item" href="{% url 'atlas:presentation_create' %}">New presentation</a></li>
<li><a class="dropdown-item" href="{% url 'atlas:pathological_process_create' %}">New pathological process</a></li>
{% endif %}
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link d-inline" href="{% url 'atlas:resource_view' %}" title="Resources"><i class="bi bi-folder2-open me-1" aria-hidden="true"></i>Resources</a>
@@ -30,7 +30,7 @@
document.getElementById('viewerstate-save-response').innerHTML = "<span class='text-danger'>Viewer state could not be retrieved.</span>";
return;
}
fetch({% if case_number %}"{% url 'atlas:collection_case_displaysetup' casedetail.collection.pk case_number=case_number %}"{% else %}"{% url 'atlas:collection_case_displaysetup_legacy' casedetail.collection.pk casedetail.case.pk %}"{% endif %}, {
fetch({% if case_number %}"{% url 'atlas:collection_case_displaysetup' casedetail.collection.pk case_number %}"{% else %}"{% url 'atlas:collection_case_displaysetup_legacy' casedetail.collection.pk casedetail.case.pk %}"{% endif %}, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -47,7 +47,7 @@
});
});
document.getElementById('reset-viewerstate').addEventListener('click', function() {
fetch({% if case_number %}"{% url 'atlas:collection_case_displaysetup' casedetail.collection.pk case_number=case_number %}"{% else %}"{% url 'atlas:collection_case_displaysetup_legacy' casedetail.collection.pk casedetail.case.pk %}"{% endif %}, {
fetch({% if case_number %}"{% url 'atlas:collection_case_displaysetup' casedetail.collection.pk case_number %}"{% else %}"{% url 'atlas:collection_case_displaysetup_legacy' casedetail.collection.pk casedetail.case.pk %}"{% endif %}, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -2,8 +2,11 @@
{% load crispy_forms_tags %}
{% block content %}
<span class="collection-name-blend">Collection: {{collection}}</span>
<h2>Case {{case_number|add:1}}
<div class="mb-2"><small class="text-muted">Collection: <strong>{{collection}}</strong></small></div>
<div class="d-flex justify-content-between align-items-start mb-3">
<div>
<h2 class="h4 mb-0">Case {{case_number|add:1}}
{% if show_title %}
: {{case.title}}
@@ -11,19 +14,36 @@
{% if question_completed %}
<span class="stamp-white">REVIEW</span>
<span class="badge bg-warning text-dark ms-2 small">REVIEW</span>
{% endif %}
</h2>
</div>
<div class="d-flex align-items-center ms-3">
<div class="dropdown">
<a class="btn btn-outline-secondary btn-sm dropdown-toggle" href="#" role="button" id="caseJump" data-bs-toggle="dropdown" aria-expanded="false"
hx-get="{% url 'atlas:collection_case_jump_partial' pk=collection.pk %}?current={{case_number}}{% if cid %}&cid={{cid}}&passcode={{passcode}}{% endif %}"
hx-target="#case-jump-menu"
hx-swap="innerHTML"
hx-trigger="click">
Jump
</a>
<div class="dropdown-menu dropdown-menu-end" id="case-jump-menu">
<div class="px-3 py-2 text-muted">Loading...</div>
</div>
</div>
</div>
</div>
{% if not question_completed and collection.question_time_limit is not None %}
<div id="question-timer-block" style="margin-top:8px; margin-bottom:8px;" title="This question has a time limit of {{ collection.question_time_limit }} seconds. The timer will start when the page loads.">
<strong>Time remaining:</strong>
<span id="question-timer" aria-live="polite">&nbsp;</span>
<div id="question-timer-progress" style="display:inline-block; vertical-align: middle; width: 200px; margin-left:12px;">
<div id="question-timer-progress-outer" style="background:#e9ecef; border-radius:6px; height:10px; overflow:hidden;">
<div id="question-timer-progress-inner" style="width:100%; height:100%; background:var(--timer-color, #28a745);"></div>
<div id="question-timer-block" class="mb-3" title="This question has a time limit of {{ collection.question_time_limit }} seconds. The timer will start when the page loads.">
<div class="d-flex align-items-center gap-3">
<div><strong>Time remaining:</strong> <span id="question-timer" aria-live="polite">&nbsp;</span></div>
<div style="flex:1; max-width:320px;">
<div class="progress" style="height:10px;">
<div id="question-timer-progress-inner" class="progress-bar" role="progressbar" style="width:100%; background:var(--timer-color, #28a745);"></div>
</div>
</div>
</div>
<div id="timer-htmx-target" style="display:none;"></div>
@@ -38,12 +58,10 @@
{% if not question_completed %}
{% if resources %}
<h5>Resources</h4>
<ul class="no-list-style">
<h5 class="mt-3">Resources</h5>
<ul class="list-group list-group-flush mb-3">
{% for caseresource in resources %}
<li>
{{caseresource.resource.get_display}}
</li>
<li class="list-group-item py-1 small">{{caseresource.resource.get_display}}</li>
{% endfor %}
</ul>
{% endif %}
@@ -51,14 +69,21 @@
{% if show_description and case.description %}
<div>
Description: {{case.description}}
<div class="mb-3">
<h6 class="mb-1">Description</h6>
<p class="mb-0">{{case.description}}</p>
</div>
{% endif %}
{% if show_history %}
<div>
History: {{casedetail.get_history_pre|linebreaks}}
<div class="card mb-3">
<div class="card-body p-2 d-flex justify-content-between align-items-start">
<div class="me-3 small text-muted">History: {{casedetail.get_history_pre|linebreaks}}</div>
{% if has_priors %}
<div class="ms-2">
<span title="This case has priors available for comparison" class="badge bg-secondary text-white rounded-pill small">Priors{% if prior_count %} ({{ prior_count }}){% endif %}</span>
</div>
{% endif %}
</div>
</div>
{% endif %}
@@ -66,9 +91,9 @@
<div>
{% if question_completed %}
<iframe id="viewer" style="width: 100%; height: 100%; border: none; padding: 0px; min-height: 700px" src="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% if case_number %}{% url 'atlas:collection_case_dicom_json_review' collection.pk case_number=case_number %}{% else %}{% url 'atlas:collection_case_dicom_json_review_legacy' collection.pk case.pk %}{% endif %}"></iframe>
<iframe id="viewer" style="width: 100%; height: 100%; border: none; padding: 0px; min-height: 700px" src="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% if case_number %}{% url 'atlas:collection_case_dicom_json_review' collection.pk case_number %}{% else %}{% url 'atlas:collection_case_dicom_json_review_legacy' collection.pk case.pk %}{% endif %}"></iframe>
{% else %}
<iframe id="viewer" style="width: 100%; height: 100%; border: none; padding: 0px; min-height: 700px" src="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% if case_number %}{% url 'atlas:collection_case_dicom_json' collection.pk case_number=case_number %}{% else %}{% url 'atlas:collection_case_dicom_json_legacy' collection.pk case.pk %}{% endif %}"></iframe>
<iframe id="viewer" style="width: 100%; height: 100%; border: none; padding: 0px; min-height: 700px" src="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% if case_number %}{% url 'atlas:collection_case_dicom_json' collection.pk case_number %}{% else %}{% url 'atlas:collection_case_dicom_json_legacy' collection.pk case.pk %}{% endif %}"></iframe>
{% endif %}
</div>
@@ -78,9 +103,9 @@
{% if collection.show_ohif_viewer_link %}
<div>
{% if question_completed %}
<a target="_blank" href="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% if case_number %}{% url 'atlas:collection_case_dicom_json_review' collection.pk case_number=case_number %}{% else %}{% url 'atlas:collection_case_dicom_json_review_legacy' collection.pk case.pk %}{% endif %}" title="Click to open the case in the advanced viewer. This will open in a new tab/window."><button class="viewer"><i class="bi bi-collection"></i> Launch advanced viewer.</button></a>
<a target="_blank" href="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% if case_number %}{% url 'atlas:collection_case_dicom_json_review' collection.pk case_number %}{% else %}{% url 'atlas:collection_case_dicom_json_review_legacy' collection.pk case.pk %}{% endif %}" title="Click to open the case in the advanced viewer. This will open in a new tab/window."><button class="viewer"><i class="bi bi-collection"></i> Launch advanced viewer.</button></a>
{% else %}
<a target="_blank" href="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% if case_number %}{% url 'atlas:collection_case_dicom_json' collection.pk case_number=case_number %}{% else %}{% url 'atlas:collection_case_dicom_json_legacy' collection.pk case.pk %}{% endif %}" title="Click to open the case in the advanced viewer. This will open in a new tab/window."><button class="viewer"><i class="bi bi-collection"></i> Launch advanced viewer.</button></a>
<a target="_blank" href="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% if case_number %}{% url 'atlas:collection_case_dicom_json' collection.pk case_number %}{% else %}{% url 'atlas:collection_case_dicom_json_legacy' collection.pk case.pk %}{% endif %}" title="Click to open the case in the advanced viewer. This will open in a new tab/window."><button class="viewer"><i class="bi bi-collection"></i> Launch advanced viewer.</button></a>
{% endif %}
</div>
{% endif %}
@@ -131,28 +156,24 @@
{% endif %}
{% if show_discussion and case.discussion %}
<p>
<details>
<summary>
Discussion:
<details class="card mb-3">
<summary class="card-header p-2" style="cursor: pointer;">
<strong>Discussion</strong>
</summary>
<div>
<div class="card-body p-2 small">
{{case.discussion|linebreaks}}
</div>
</details>
</p>
{% endif %}
{% if show_report and case.report %}
<p>
<details>
<summary>
Report:
<details class="card mb-3">
<summary class="card-header p-2" style="cursor: pointer;">
<strong>Report</strong>
</summary>
<div>
<div class="card-body p-2 small">
{{case.report|linebreaks}}
</div>
</details>
</p>
{% endif %}
{% if question_completed %}
@@ -246,25 +267,28 @@
{% endif %}
{% endif %}
<div class="mb-2">
{% if previous %}
<button type="submit" name="previous" class="save btn btn-default">Previous</button>
<button type="submit" name="previous" class="btn btn-outline-secondary btn-sm me-2">Previous</button>
{% endif %}
{% if next %}
<button type="submit" name="next" class="save btn btn-default">Next</button>
<button type="submit" name="next" class="btn btn-primary btn-sm me-2">Next</button>
{% elif collection.collection_type == "REP" %}
{% if not exam.publish_results %}
<button type="submit" name="save" class="save btn btn-default">Save</button>
<button type="submit" name="save" class="btn btn-primary btn-sm me-2">Save</button>
{% endif %}
{% endif %}
</div>
{% if collection.self_review and not collection.feedback_once_collection_complete and not question_completed %}
<button type="submit" name="complete_case" class="save btn btn-default">Finish Case</button>
<button type="submit" name="complete_case" class="btn btn-success btn-sm">Finish Case</button>
{% endif %}
<br />
<button type="submit" name="finish" class="save btn btn-default">Overview</button>
<div class="mt-3">
<button type="submit" name="finish" class="btn btn-outline-secondary btn-sm">Overview</button>
<button type="submit" id="goto-button" value="test" name="goto" class="hide">goto</button>
</div>
</form>
<style>
label {
@@ -0,0 +1,22 @@
{% extends 'atlas/base.html' %}
{% load render_table from django_tables2 %}
{% block content %}
<div class="container-fluid">
<div class="d-flex align-items-start justify-content-between mb-3">
<h2 class="mb-0">Collections</h2>
{% if request.user.is_staff %}
<a class="btn btn-sm btn-primary" href="{% url 'atlas:exam_create' %}">Create collection</a>
{% endif %}
</div>
<p class="mb-3">Manage and browse case collections. Use filters to narrow results.</p>
{% render_table table %}
{% include "generic/partials/filter_bar.html" with filter=filter app_name=app_name collapse_id="bottom-filter-body" %}
</div>
{% endblock %}
+4 -6
View File
@@ -18,7 +18,7 @@
<h5 class="mb-2">Details</h5>
<dl class="row">
<dt class="col-sm-4">Primary name</dt>
<dd class="col-sm-8">{{ condition.primary }}</dd>
<dd class="col-sm-8">{% if condition.canonical %}No (alias of <a href="{{ condition.canonical.get_absolute_url }}">{{ condition.canonical.name }}</a>){% else %}Yes{% endif %}</dd>
<dt class="col-sm-4">Subspecialty</dt>
<dd class="col-sm-8">
@@ -31,11 +31,9 @@
<dt class="col-sm-4">Synonyms</dt>
<dd class="col-sm-8">
{% for syn in condition.synonym.all %}
<a class="badge bg-secondary text-decoration-none text-white me-1" href="{{ syn.get_absolute_url }}">{{ syn }}</a>
{% empty %}
&mdash;
{% endfor %}
<div id="synonyms-container">
{% include 'atlas/partials/_synonyms_list.html' %}
</div>
</dd>
<dt class="col-sm-4">Parent</dt>
+7 -14
View File
@@ -1,27 +1,20 @@
{% extends "atlas/base.html" %}
<!-- {% load static from static %} -->
{% load crispy_forms_tags %}
{% block css %}{% endblock %}
{% block css %}
{% endblock %}
{% block js %}
<!--<script type="text/javascript" src="/admin/jsi18n/"></script>-->
{{ form.media }}
<script type="text/javascript">
</script>
<!-- {{ form.media }} -->
{% endblock %}
{% block content %}
<h2>Add / Edit Condition</h2>
<p>Use this form to create or edit a condition.</p>
<p>Please check if it already <a href='{% url "atlas:condition_view" %}'>exists</a> before doing so!</p>
<form action="" method="post" enctype="multipart/form-data" id="condition-form">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" class="submit-button" value="Submit" name="submit">
{% crispy form %}
</form>
{% endblock %}
+2 -2
View File
@@ -12,8 +12,8 @@
</div>
<div>
<h3>Name: {{finding.name}}</h3>
Primary name: {{finding.primary}}<br />
Synonyms: {{finding.synonym.all|join:", "}}<br />
Primary name: {% if finding.canonical %}No (alias of <a href="{{ finding.canonical.get_absolute_url }}">{{ finding.canonical.name }}</a>){% else %}Yes{% endif %}<br />
Synonyms: {{ finding.get_synonym_link|safe }}<br />
</div>
{% if finding.seriesfinding_set.all %}
<h4>Associated Cases</h4>
@@ -0,0 +1,11 @@
{% for cd in casedetails %}
{% with idx=forloop.counter0 %}
{% if cid %}
<a class="dropdown-item {% if idx == current %}active{% endif %}" href="{% url 'atlas:collection_case_view_take' pk=collection.pk case_number=idx cid=cid passcode=passcode %}">
{% else %}
<a class="dropdown-item {% if idx == current %}active{% endif %}" href="{% url 'atlas:collection_case_view_take_user' pk=collection.pk case_number=idx %}">
{% endif %}
Case {{ forloop.counter }}: {{ cd.case.title|default:cd.case.pk|truncatechars:60 }}
</a>
{% endwith %}
{% endfor %}
@@ -27,7 +27,7 @@
{% if not added %}
<form class="row g-2"
{% if case_number %}
hx-post="{% url 'atlas:collection_case_priors' collection.id case_number=case_number %}"
hx-post="{% url 'atlas:collection_case_priors' collection.id case_number %}"
{% else %}
hx-post="{% url 'atlas:collection_case_priors_legacy' collection.id casedetail.case.pk %}"
{% endif %}
@@ -51,7 +51,7 @@
{% else %}
<form
{% if case_number %}
hx-post="{% url 'atlas:collection_case_priors' collection.id case_number=case_number %}"
hx-post="{% url 'atlas:collection_case_priors' collection.id case_number %}"
{% else %}
hx-post="{% url 'atlas:collection_case_priors_legacy' collection.id casedetail.case.pk %}"
{% endif %}
@@ -0,0 +1,56 @@
{% comment %}Partial that renders the synonyms list + add form. Used by condition_detail and HTMX responses.{% endcomment %}
{% load static %}
{% with syns=condition.get_synonyms %}
{% if syns %}
{% for syn in syns %}
<a class="badge bg-secondary text-decoration-none text-white me-1" href="{{ syn.get_absolute_url }}">{{ syn }}</a>
{% endfor %}
{% else %}
&mdash;
{% endif %}
{% endwith %}
{% if request.user.is_authenticated and can_merge %}
<div class="mt-2 d-flex gap-2">
<!-- Button to add an existing condition as a synonym -->
<a class="btn btn-sm btn-outline-primary" data-bs-toggle="collapse" href="#addSynonymCollapse" role="button" aria-expanded="false" aria-controls="addSynonymCollapse">Add synonym</a>
<!-- Button to create a new condition and add it as a synonym -->
<a class="btn btn-sm btn-outline-success" data-bs-toggle="collapse" href="#createSynonymCollapse" role="button" aria-expanded="false" aria-controls="createSynonymCollapse">Create synonym</a>
</div>
<!-- Collapse: add existing condition -->
<div class="collapse mt-2" id="addSynonymCollapse">
<div class="card card-body">
<form method="POST"
hx-post="{% url 'atlas:condition_detail' condition.pk %}"
hx-target="#synonyms-container" hx-swap="innerHTML">
{% csrf_token %}
<input type="hidden" name="action" value="add_synonym" />
<div class="mb-2">
<label class="form-label small">Select existing condition</label>
{{ synonym_form.condition }}
</div>
<button class="btn btn-primary btn-sm" type="submit">Add</button>
</form>
</div>
</div>
<!-- Collapse: create new condition -->
<div class="collapse mt-2" id="createSynonymCollapse">
<div class="card card-body">
<form method="POST"
hx-post="{% url 'atlas:condition_detail' condition.pk %}"
hx-target="#synonyms-container" hx-swap="innerHTML">
{% csrf_token %}
<input type="hidden" name="action" value="add_synonym" />
<div class="mb-2">
<label class="form-label small">Create new synonym name</label>
<input class="form-control" type="text" name="synonym_name" placeholder="e.g. Granulomatosis with Polyangitis" required />
</div>
<button class="btn btn-success btn-sm" type="submit">Create</button>
</form>
</div>
</div>
{% endif %}
@@ -0,0 +1,31 @@
{% load static %}
<div class="series-images-list">
{% for image in images %}
<div class="d-flex align-items-center mb-2">
{% if image.image %}
<a href="{% url 'atlas:series_image_dicom' pk=image.pk %}" target="_blank" class="me-2">
<img src="{{ image.image.url }}" alt="image-{{ image.pk }}" style="width:96px;height:auto;object-fit:cover;border-radius:.25rem;" class="img-thumbnail">
</a>
{% else %}
<div class="me-2 bg-secondary" style="width:96px;height:72px;border-radius:.25rem;"></div>
{% endif %}
<div class="flex-grow-1">
<div><strong>{{ image.image.name|default:"(no file)" }}</strong></div>
{% if image.image %}
<div class="small text-muted">{{ image.image.size|filesizeformat }}</div>
{% endif %}
{% if image.image_blake3_hash %}
<div class="small text-muted">hash: {{ image.image_blake3_hash|truncatechars:12 }}</div>
{% endif %}
</div>
<div class="ms-auto text-end">
<a href="{% url 'atlas:series_image_dicom' pk=image.pk %}" class="btn btn-sm btn-outline-secondary">View DICOM</a>
</div>
</div>
{% empty %}
<p class="text-muted">No images found for this series.</p>
{% endfor %}
</div>
@@ -0,0 +1,23 @@
{% extends "atlas/base.html" %}
{% load crispy_forms_tags %}
{% block js %}
{{ form.media }}
{% endblock %}
{% block content %}
<h2>Add / Edit Pathological process</h2>
<p>Use this form to create or edit a pathological process.</p>
<p>Please check if it already <a href='{% url "atlas:pathological_process_view" %}'>exists</a> before doing so!</p>
<form action="" method="post" enctype="multipart/form-data" id="pathological-process-form">
{% csrf_token %}
{% crispy form %}
<div class="mt-3">
<button type="submit" class="btn btn-primary">Submit</button>
<a class="btn btn-secondary ms-2" href="{% url 'atlas:pathological_process_view' %}">Cancel</a>
</div>
</form>
{% endblock %}
@@ -0,0 +1,23 @@
{% extends "atlas/base.html" %}
{% load crispy_forms_tags %}
{% block js %}
{{ form.media }}
{% endblock %}
{% block content %}
<h2>Add / Edit Presentation</h2>
<p>Use this form to create or edit a presentation.</p>
<p>Please check if it already <a href='{% url "atlas:presentation_view" %}'>exists</a> before doing so!</p>
<form action="" method="post" enctype="multipart/form-data" id="presentation-form">
{% csrf_token %}
{% crispy form %}
<div class="mt-3">
<button type="submit" class="btn btn-primary">Submit</button>
<a class="btn btn-secondary ms-2" href="{% url 'atlas:presentation_view' %}">Cancel</a>
</div>
</form>
{% endblock %}
+25 -1
View File
@@ -49,7 +49,6 @@
<div class="ms-auto text-muted small">{{ series.get_image_count }} images</div>
</div>
</div>
<div class="mt-3">
<!-- Finding form moved below the viewport -->
<div class="card mt-3">
@@ -114,6 +113,31 @@
</div>
</details>
</div>
<!-- Images (loaded on demand via HTMX) -->
<div class="card mt-3">
<div class="card-header d-flex justify-content-between align-items-center">
<span>Images</span>
<div>
<button id="load-images-button" class="btn btn-sm btn-outline-primary"
hx-get="{% url 'atlas:series_images' series.pk %}"
hx-target="#series-images-container"
hx-swap="innerHTML"
hx-trigger="click"
hx-on="htmx:beforeRequest: document.getElementById('images-loading-indicator').style.display='inline-block'; htmx:afterSwap: document.getElementById('images-loading-indicator').style.display='none'; document.getElementById('load-images-button').disabled = true">
Load images
</button>
<a href="{% url 'atlas:series_download' series.pk %}" class="btn btn-sm btn-outline-success ms-2" target="_blank" rel="noopener">Download</a>
<span id="images-loading-indicator" class="spinner-border spinner-border-sm ms-2" role="status" aria-hidden="true" style="display:none"></span>
</div>
</div>
<div class="card-body">
<div id="series-images-container">
<p class="text-muted small">Click 'Load images' to fetch.</p>
</div>
</div>
</div>
</div>
<div class="col-md-4 mb-3">
+2 -2
View File
@@ -14,8 +14,8 @@
</div>
<div>
<h3>Name: {{structure.name}}</h3>
Primary name: {{structure.primary}}<br />
Synonyms: {{structure.synonym.all|join:", "}}<br />
Primary name: {% if structure.canonical %}No (alias of <a href="{{ structure.canonical.get_absolute_url }}">{{ structure.canonical.name }}</a>){% else %}Yes{% endif %}<br />
Synonyms: {{ structure.get_synonym_link|safe }}<br />
</div>
<h4>Associated Cases</h4>
<ul>
@@ -0,0 +1,23 @@
{% extends "atlas/base.html" %}
{% load crispy_forms_tags %}
{% block js %}
{{ form.media }}
{% endblock %}
{% block content %}
<h2>Add / Edit Subspecialty</h2>
<p>Use this form to create or edit a subspecialty.</p>
<p>Please check if it already <a href='{% url "atlas:subspecialty_view" %}'>exists</a> before doing so!</p>
<form action="" method="post" enctype="multipart/form-data" id="subspecialty-form">
{% csrf_token %}
{% crispy form %}
<div class="mt-3">
<button type="submit" class="btn btn-primary">Submit</button>
<a class="btn btn-secondary ms-2" href="{% url 'atlas:subspecialty_view' %}">Cancel</a>
</div>
</form>
{% endblock %}
+8 -2
View File
@@ -7,7 +7,14 @@
{% block content %}
<div class="container-fluid">
<h2>My Collections</h2>
<div class="d-flex align-items-start justify-content-between">
<h2 class="mb-0">{{ model_verbose_name_plural|capfirst }}</h2>
{% if request.user.is_staff and create_url %}
<div>
<a class="btn btn-sm btn-primary" href="{{ create_url }}">Add new {{ model_verbose_name }}</a>
</div>
{% endif %}
</div>
{% comment %} <details>
<summary>
<h4>Filter</h4>
@@ -19,7 +26,6 @@
</form>
</div>
</details> {% endcomment %}
View my <a href='{% url "atlas:case_view" %}?author={{request.user.id}}'>cases</a>.
{% render_table table %}
{% include "generic/partials/filter_bar.html" with filter=filter app_name=app_name collapse_id="bottom-filter-body" %}
</div>
+9
View File
@@ -112,6 +112,11 @@ urlpatterns = [
views.CollectionCaseUpdate.as_view(),
name="collection_case_update",
),
path(
"collection/<int:pk>/case_jump",
views.collection_case_jump_partial,
name="collection_case_jump_partial",
),
path(
"collection/add_cases",
views.add_cases_to_collection,
@@ -423,6 +428,7 @@ urlpatterns = [
path(
"subspecialty/<int:pk>", views.subspecialty_detail, name="subspecialty_detail"
),
path("subspecialty/create", views.SubspecialtyCreate.as_view(), name="subspecialty_create"),
path("condition/create", views.ConditionCreate.as_view(), name="condition_create"),
path("finding/", views.FindingView.as_view(), name="finding_view"),
path("finding/<int:pk>", views.finding_detail, name="finding_detail"),
@@ -451,6 +457,7 @@ urlpatterns = [
# TODO: case context series viewing (so that we can view series in the context of a case)
path("series/<int:pk>", views.series_detail, name="series_detail"),
path("series/<int:pk>/viewer", views.series_viewer, name="series_viewer"),
path("series/<int:pk>/images/", views.series_images_partial, name="series_images"),
path("series/<int:pk>/authors", views.SeriesAuthorUpdate.as_view(), name="series_authors"),
path("series/<int:series_id>/finding/related", views.series_finding_related, name="series_finding_related"),
path("series/", views.SeriesView.as_view(), name="series_view"),
@@ -596,6 +603,7 @@ urlpatterns = [
path(
"presentation/<int:pk>", views.presentation_detail, name="presentation_detail"
),
path("presentation/create", views.PresentationCreate.as_view(), name="presentation_create"),
path(
"process/",
views.PathologicalProcessView.as_view(),
@@ -606,6 +614,7 @@ urlpatterns = [
views.pathological_process_detail,
name="pathological_process_detail",
),
path("process/create", views.PathologicalProcessCreate.as_view(), name="pathological_process_create"),
path("combine_series/", views.combine_series, name="combine_series"),
path(
"case/<int:case_id>/linked/",
+224 -18
View File
@@ -40,6 +40,7 @@ from .tables import ResourceTable
from django.views.decorators.csrf import csrf_exempt
from django.urls import reverse_lazy, reverse
from django.urls.exceptions import NoReverseMatch
from django.http import Http404, JsonResponse
from django.http import HttpResponseRedirect, HttpResponse
@@ -82,6 +83,9 @@ from .forms import (
SeriesFindingForm,
CaseDifferentialFormSet,
StructureForm,
SubspecialtyForm,
PresentationForm,
PathologicalProcessForm,
UserQuestionAnswerForm,
UserReportAnswerForm,
)
@@ -792,6 +796,17 @@ def series_detail(request, pk, finding_pk=None):
)
@login_required
@user_is_author_or_atlas_series_checker_or_atlas_marker_or_open_access
def series_images_partial(request, pk):
"""Return a small fragment that lists images for a series. Intended for HTMX."""
series = get_object_or_404(Series, pk=pk)
logger.debug(series)
images = series.images.filter(removed=False).order_by("pk")
logger.debug(images)
return render(request, "atlas/partials/series_images.html", {"series": series, "images": images})
@login_required
# @user_is_atlas_editor
def question_schema_detail(request, pk: int):
@@ -826,7 +841,12 @@ def question_schema_schemas(request):
def condition_detail(request, pk):
condition = get_object_or_404(Condition, pk=pk)
form = ConditionAutocompleteForm()
# form used for the merge UI
merge_form = ConditionAutocompleteForm()
# form used to add a synonym (can post either an existing condition via autocomplete
# or provide a plain name in 'synonym_name')
synonym_form = ConditionAutocompleteForm()
can_merge = False
@@ -836,11 +856,78 @@ def condition_detail(request, pk):
):
can_merge = True
# Handle POST to add a synonym
if request.method == "POST" and request.POST.get("action") == "add_synonym":
# only allow staff/editors
if not (
request.user.is_superuser
or request.user.groups.filter(name="atlas_editor").exists()
):
return HttpResponse("Forbidden", status=403)
# Try autocomplete-selected condition first
form = ConditionAutocompleteForm(request.POST)
other = None
if form.is_valid():
other = form.cleaned_data.get("condition")
# keep the form (possibly with errors) to render back in HTMX responses
synonym_form = form
# If no autocomplete selection, accept a free-text name
synonym_name = request.POST.get("synonym_name")
if not other and synonym_name:
other, created = Condition.objects.get_or_create(name=synonym_name)
if created:
# created condition: treat as alias by setting canonical below
pass
if other and other != condition:
# Option B: treat synonym as alias/canonical relationship.
# Determine canonical/master for the current condition
master = condition.canonical if condition.canonical else condition
# If `other` belongs to a different canonical group, move its group
# to point at our master. If `other` has no canonical, set it.
if other.canonical:
# move the whole other group (canonical + aliases) to our master
group_master = other.canonical
members = Condition.objects.filter(Q(canonical=group_master) | Q(pk=group_master.pk))
for m in members:
if m.pk != master.pk:
m.canonical = master
m.save()
else:
# other is standalone; make it an alias of our master
other.canonical = master
other.save()
# Master is indicated by having no `canonical` pointer. Ensure
# it remains canonical (no save required unless changed elsewhere).
# If this was an HTMX request return the updated synonyms partial so the
# page can be updated without a full redirect. Otherwise perform the
# existing redirect back to the detail page.
if request.htmx:
html = render_to_string(
"atlas/partials/_synonyms_list.html",
{"condition": condition, "synonym_form": synonym_form, "can_merge": can_merge},
request=request,
)
return HttpResponse(html)
return redirect("atlas:condition_detail", pk=condition.pk)
# logging.debug(atlas.subspecialty.first().name.all())
return render(
request,
"atlas/condition_detail.html",
{"condition": condition, "form": form, "can_merge": can_merge},
{
"condition": condition,
"form": merge_form,
"synonym_form": synonym_form,
"can_merge": can_merge,
},
)
@@ -1058,6 +1145,46 @@ def collection_options(request):
html = render_to_string("atlas/partials/collection_options.html", {"collections": collections}, request=request)
return HttpResponse(html)
@login_required
def collection_case_jump_partial(request, pk: int):
"""Return an HTMX partial containing a jump list for cases in the collection.
Expects optional GET params:
- current: the current case index (0-based) to mark active
- cid, passcode: optional candidate identifiers so links include them when present
"""
# Allow non-HTMX callers to still get the fragment (useful for testing)
collection = get_object_or_404(CaseCollection, pk=pk)
casedetails = (
CaseDetail.objects.filter(collection=collection)
.select_related('case')
.order_by('sort_order')
)
try:
current = int(request.GET.get('current', 0) or 0)
except Exception:
current = 0
cid = request.GET.get('cid')
passcode = request.GET.get('passcode')
html = render_to_string(
'atlas/partials/_collection_case_jump.html',
{
'collection': collection,
'casedetails': casedetails,
'current': current,
'cid': cid,
'passcode': passcode,
},
request=request,
)
return HttpResponse(html)
@login_required
def remove_cases_from_collection(request):
if not request.htmx:
@@ -1685,6 +1812,24 @@ class StructureCreate(RevisionMixin, LoginRequiredMixin, CreateView):
form_class = StructureForm
class SubspecialtyCreate(RevisionMixin, LoginRequiredMixin, CreateView):
model = Subspecialty
form_class = SubspecialtyForm
template_name = "atlas/subspecialty_form.html"
class PresentationCreate(RevisionMixin, LoginRequiredMixin, CreateView):
model = Presentation
form_class = PresentationForm
template_name = "atlas/presentation_form.html"
class PathologicalProcessCreate(RevisionMixin, LoginRequiredMixin, CreateView):
model = PathologicalProcess
form_class = PathologicalProcessForm
template_name = "atlas/pathological_process_form.html"
class AtlasCreateBase(RevisionMixin, LoginRequiredMixin):
model = Case
form_class = CaseForm
@@ -2119,6 +2264,17 @@ class ConditionView(LoginRequiredMixin, UserConfigurablePaginationMixin, SingleT
filterset_class = ConditionFilter
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
try:
ctx["create_url"] = reverse(f"atlas:{self.model._meta.model_name}_create")
except NoReverseMatch:
ctx["create_url"] = None
# Provide verbose names to templates without accessing _meta in templates
ctx["model_verbose_name"] = getattr(self.model._meta, "verbose_name", None)
ctx["model_verbose_name_plural"] = getattr(self.model._meta, "verbose_name_plural", None)
return ctx
class QuestionSchemaView(LoginRequiredMixin, UserConfigurablePaginationMixin, SingleTableMixin, FilterView):
model = QuestionSchema
@@ -2135,6 +2291,16 @@ class SubspecialtyView(LoginRequiredMixin, UserConfigurablePaginationMixin, Sing
filterset_class = SubspecialtyFilter
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
try:
ctx["create_url"] = reverse(f"atlas:{self.model._meta.model_name}_create")
except NoReverseMatch:
ctx["create_url"] = None
ctx["model_verbose_name"] = getattr(self.model._meta, "verbose_name", None)
ctx["model_verbose_name_plural"] = getattr(self.model._meta, "verbose_name_plural", None)
return ctx
class PresentationView(LoginRequiredMixin, UserConfigurablePaginationMixin, SingleTableMixin, FilterView):
model = Presentation
@@ -2143,6 +2309,16 @@ class PresentationView(LoginRequiredMixin, UserConfigurablePaginationMixin, Sing
filterset_class = PresentationFilter
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
try:
ctx["create_url"] = reverse(f"atlas:{self.model._meta.model_name}_create")
except NoReverseMatch:
ctx["create_url"] = None
ctx["model_verbose_name"] = getattr(self.model._meta, "verbose_name", None)
ctx["model_verbose_name_plural"] = getattr(self.model._meta, "verbose_name_plural", None)
return ctx
class PathologicalProcessView(LoginRequiredMixin, UserConfigurablePaginationMixin, SingleTableMixin, FilterView):
model = PathologicalProcess
@@ -2151,6 +2327,16 @@ class PathologicalProcessView(LoginRequiredMixin, UserConfigurablePaginationMixi
filterset_class = PathologicalProcessFilter
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
try:
ctx["create_url"] = reverse(f"atlas:{self.model._meta.model_name}_create")
except NoReverseMatch:
ctx["create_url"] = None
ctx["model_verbose_name"] = getattr(self.model._meta, "verbose_name", None)
ctx["model_verbose_name_plural"] = getattr(self.model._meta, "verbose_name_plural", None)
return ctx
class StructureView(LoginRequiredMixin, UserConfigurablePaginationMixin, SingleTableMixin, FilterView):
model = Structure
@@ -2159,6 +2345,16 @@ class StructureView(LoginRequiredMixin, UserConfigurablePaginationMixin, SingleT
filterset_class = StructureFilter
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
try:
ctx["create_url"] = reverse(f"atlas:{self.model._meta.model_name}_create")
except NoReverseMatch:
ctx["create_url"] = None
ctx["model_verbose_name"] = getattr(self.model._meta, "verbose_name", None)
ctx["model_verbose_name_plural"] = getattr(self.model._meta, "verbose_name_plural", None)
return ctx
class FindingView(LoginRequiredMixin, UserConfigurablePaginationMixin, SingleTableMixin, FilterView):
model = Finding
@@ -2167,6 +2363,14 @@ class FindingView(LoginRequiredMixin, UserConfigurablePaginationMixin, SingleTab
filterset_class = FindingFilter
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
try:
ctx["create_url"] = reverse(f"atlas:{self.model._meta.model_name}_create")
except NoReverseMatch:
ctx["create_url"] = None
return ctx
@login_required
def case_order_dicom(request, pk):
@@ -2527,7 +2731,7 @@ def categories_search_partial(request):
class CollectionView(LoginRequiredMixin, SingleTableMixin, FilterView):
model = CaseCollection
table_class = CaseCollectionTable
template_name = "atlas/view.html"
template_name = "atlas/collection_view.html"
filterset_class = CaseCollectionFilter
@@ -2951,6 +3155,9 @@ def collection_case_priors(request, exam_id, case_number):
previous = collection.get_previous_case(casedetail.case)
next = collection.get_next_case(casedetail.case)
# Determine whether the current user can edit this collection/case so
# included fragments which rely on `can_edit` have the value available.
can_edit = request.user.is_superuser or collection.author.filter(pk=request.user.pk).exists()
return render(
request,
@@ -2968,20 +3175,19 @@ def collection_case_priors(request, exam_id, case_number):
"case_number": case_number,
"added_priors": added_priors,
"available_priors": available_priors,
"can_edit": can_edit,
# Provide a default `error` value so `{% if error %}` checks in included
# partials won't raise during variable resolution when the key is absent.
"error": None,
},
)
@user_is_collection_author_or_atlas_editor
def collection_case_questions(request, exam_id, case_id):
# Support either case_number (index) or case_id (case PK)
try:
casedetail = CaseDetail.objects.get(case=case_id, collection=exam_id)
collection = casedetail.collection
except Exception:
def collection_case_questions(request, exam_id, case_number):
collection = get_object_or_404(CaseCollection, pk=exam_id)
try:
case_obj = collection.get_case_by_index(int(case_id))
case_obj = collection.get_case_by_index(case_number)
casedetail = CaseDetail.objects.get(case=case_obj, collection=collection)
except Exception:
raise Http404("Case not found in collection")
@@ -3094,17 +3300,11 @@ def collection_case_questions(request, exam_id, case_id):
)
@user_is_collection_author_or_atlas_editor
def collection_case_details(request, exam_id, case_id):
def collection_case_details(request, exam_id, case_number):
# Accept either case_number (index into collection) or case_id (case PK).
casedetail = None
collection = None
try:
casedetail = CaseDetail.objects.get(case=case_id, collection=exam_id)
collection = casedetail.collection
except Exception:
collection = get_object_or_404(CaseCollection, pk=exam_id)
try:
case_obj = collection.get_case_by_index(int(case_id))
case_obj = collection.get_case_by_index(int(case_number))
casedetail = CaseDetail.objects.get(case=case_obj, collection=collection)
except Exception:
raise Http404("Case not found in collection")
@@ -3653,6 +3853,10 @@ def collection_case_view_take(
case _:
continue
# Determine whether any prior series will be shown to the candidate.
has_priors = any(prior_flag for (_, prior_flag, _) in series_to_load)
prior_count = prior_cases.count()
return render(
request,
"atlas/collection_case_view_take.html",
@@ -3663,6 +3867,8 @@ def collection_case_view_take(
"casedetail": casedetail,
"series_list": series_list,
"series_to_load": series_to_load,
"has_priors": has_priors,
"prior_count": prior_count,
"case_number": case_number,
"previous": previous,
"next": next,
+30
View File
@@ -0,0 +1,30 @@
upstream app_server {
server web:8000;
}
server {
listen 80;
listen [::]:80;
server_name _;
client_max_body_size 100M;
location /static/ {
alias /usr/src/app/static/;
expires 30d;
add_header Cache-Control "public, max-age=2592000";
}
location /media {
alias /usr/src/app/media;
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
proxy_redirect off;
proxy_buffering off;
proxy_pass http://app_server;
}
}
+127
View File
@@ -0,0 +1,127 @@
upstream app_server {
# In production we proxy to the 'web' service (gunicorn) listening on 8000
server web:8000;
}
server {
listen 80;
listen [::]:80;
server_name _;
client_max_body_size 100M;
# Serve static files from the static volume
location /static/ {
alias /usr/src/app/static/;
expires 30d;
add_header Cache-Control "public, max-age=2592000";
}
# Serve media files from the media volume. CORS handling preserved.
set $cors "";
if ($http_origin ~* (https?://(localhost:5173|viewer\.penracourses\.org\.uk))) {
set $cors $http_origin;
}
location /media {
if ($request_method = OPTIONS ) {
add_header 'Access-Control-Allow-Origin' $cors always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Headers' "Origin, X-Requested-With, Content-Type, Accept" always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 200;
}
add_header 'Access-Control-Allow-Origin' $cors always;
alias /usr/src/app/media;
}
# Viewer / OHIF / other static frontends - mount these into the nginx container at deploy time
location /viewer {
alias /srv/www/viewer;
index index.html;
try_files $uri $uri/ /viewer/index.html;
add_header Cache-Control "no-store, no-cache, must-revalidate";
add_header 'Cross-Origin-Resource-Policy' 'cross-origin';
}
location /ohif {
add_header 'Cross-Origin-Opener-Policy' 'same-origin' always;
add_header 'Cross-Origin-Embedder-Policy' 'require-corp' always;
add_header 'Cross-Origin-Resource-Policy' 'same-site' always;
alias /srv/www/ohif;
try_files $uri /ohif/index.html;
}
# rts and other host-mounted folders
location /rts {
alias /srv/www/rts;
}
location /rota {
alias /srv/proc/rota;
autoindex on;
}
location /uploader {
alias /srv/uploader;
autoindex on;
}
# Reporter proxy - if you run a reporter service, set it up on the 'reporter' network name
location ~ ^/reporter/(.*)$ {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Authorization $http_authorization;
proxy_pass_header Authorization;
proxy_pass http://reporter:5129/$1?$args;
proxy_set_header X-Forwarded-Prefix /reporter;
proxy_redirect http://reporter:5129/ /reporter/;
}
# Default proxy to the Django/gunicorn upstream
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
proxy_redirect off;
proxy_buffering off;
add_header 'Cross-Origin-Embedder-Policy' 'require-corp' always;
add_header 'Cross-Origin-Resource-Policy' 'same-site' always;
proxy_pass http://app_server;
}
# Default dev / health server block; keep 443 managed outside of docker unless you mount certs
}
# A minimal HTTPS server block that expects certs to be mounted at /etc/letsencrypt
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name www.penracourses.org.uk penracourses.org.uk viewer.penracourses.org.uk;
ssl_certificate /etc/letsencrypt/live/www.penracourses.org.uk/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/www.penracourses.org.uk/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
client_max_body_size 4G;
# Same static/media handling as above
location /static/ { alias /usr/src/app/static/; }
location /media { alias /usr/src/app/media; }
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
proxy_redirect off;
proxy_buffering off;
proxy_pass http://app_server;
}
}
+122
View File
@@ -0,0 +1,122 @@
"""
Example `settings_local.py` derived from the production server file.
This file is a template only DO NOT commit real secrets. Copy it to
`rad/deploy/settings_local.py` on your server (or provide your own) and
ensure the real file is excluded from git.
"""
import os
DEBUG = True
INTERNAL_IPS = ["82.69.88.125", "217.155.198.96", "localhost", "127.0.0.1"]
# When running in Docker (dev), requests will often come from an internal
# container/network address. Add any discovered host/container IPs (and a
# likely gateway address) to INTERNAL_IPS so the debug toolbar can render.
if DEBUG:
try:
import socket
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
for ip in ips:
if ip not in INTERNAL_IPS:
INTERNAL_IPS.append(ip)
# common docker gateway pattern: replace last octet with '1'
parts = ip.split('.')
if len(parts) == 4:
parts[-1] = '1'
gw = '.'.join(parts)
if gw not in INTERNAL_IPS:
INTERNAL_IPS.append(gw)
except Exception:
# best-effort only; don't fail startup if this lookup doesn't work
pass
# In local/dev enable the toolbar unconditionally to avoid IP/proxy
# headaches while developing inside Docker/behind nginx.
DEBUG_TOOLBAR_CONFIG = {
"SHOW_TOOLBAR_CALLBACK": lambda request: True,
}
# Paths inside the nginx container / host-mounted deploy directories.
# On the server, these paths are mounted into nginx as described in the
# deployment README. Adjust as needed.
STATIC_ROOT = '/usr/src/app/static/'
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
if not DEBUG:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt': "%d/%b/%Y %H:%M:%S",
},
'simple': {
'format': '%(levelname)s %(message)s',
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'log.txt',
'formatter': 'verbose',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'propagate': True,
'level': 'DEBUG',
},
'atlas': {
'handlers': ['file'],
'level': 'DEBUG',
},
}
}
# External service credentials (placeholders)
CIMAR_USERNAME = "your.username@example.com"
CIMAR_PASSWORD = "<REPLACE-WITH-SECRET>"
# Celery settings — when running in docker the redis service is
# reachable at the `redis` hostname provided by docker compose.
CELERY_BROKER_URL = "redis://redis:6379"
CELERY_RESULT_BACKEND = "redis://redis:6379"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": os.environ.get("DB_NAME", "django"),
"USER": os.environ.get("DB_USER", "django"),
"PASSWORD": os.environ.get("DB_PASSWORD", "AVNS_NG_s4i7SMMobWLO"),
#"HOST": os.environ.get("DB_HOST", "db-postgresql-lon1-05515-do-user-8165014-0.b.db.ondigitalocean.com"),
"HOST": os.environ.get("DB_HOST", "db-postgresql-lon1-05515-jan-22-backup-do-user-8165014-0.c.db.ondigitalocean.com"),
"PORT": os.environ.get("DB_PORT", "25060"),
#"NAME": os.environ.get("DB_NAME", "django"),
#"USER": os.environ.get("DB_USER", "django"),
#"PASSWORD": os.environ.get("DB_PASSWORD", "f7bf31dc9bda1256ea827953480d1917"),
#"HOST": os.environ.get("DB_HOST", "161.35.163.87"),
#"PORT": os.environ.get("DB_PORT", "5432"),
}
}
# Development overrides to avoid forcing HTTPS and secure cookies in local dev
# (production should keep these True).
SECURE_SSL_REDIRECT = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
SECURE_HSTS_SECONDS = 0
# Allow requests from the local dev nginx/dev server and direct runserver
# (include scheme+host+port for Django's origin checking).
CSRF_TRUSTED_ORIGINS = [
"http://127.0.0.1:8000",
"http://localhost:8000",
]
REMOTE_URL = "http://127.0.0.1:8000"
+60
View File
@@ -0,0 +1,60 @@
"""
Example `settings_local.py` derived from the production server file.
This file is a template only — DO NOT commit real secrets. Copy it to
`rad/deploy/settings_local.py` on your server (or provide your own) and
ensure the real file is excluded from git.
"""
DEBUG = False
INTERNAL_IPS = ["82.69.88.125", "217.155.198.96"]
# Paths inside the nginx container / host-mounted deploy directories.
# On the server, these paths are mounted into nginx as described in the
# deployment README. Adjust as needed.
STATIC_ROOT = '/usr/src/app/static/'
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
if not DEBUG:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt': "%d/%b/%Y %H:%M:%S",
},
'simple': {
'format': '%(levelname)s %(message)s',
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'log.txt',
'formatter': 'verbose',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'propagate': True,
'level': 'DEBUG',
},
'atlas': {
'handlers': ['file'],
'level': 'DEBUG',
},
}
}
# External service credentials (placeholders)
CIMAR_USERNAME = "your.username@example.com"
CIMAR_PASSWORD = "<REPLACE-WITH-SECRET>"
# Celery settings — when running in docker the redis service is
# reachable at the `redis` hostname provided by docker compose.
CELERY_BROKER_URL = "redis://redis:6379"
CELERY_RESULT_BACKEND = "redis://redis:6379"
+69
View File
@@ -0,0 +1,69 @@
# Development override: point the web service to rad/.env.dev and map nginx to
# non-privileged host ports so you can run without sudo.
services:
web:
env_file:
- ../.env.dev
# Development: run Django's autoreloading development server instead of
# the production entrypoint/gunicorn. Mount the repository into the
# container so code edits on the host trigger Django's autoreload.
entrypoint: ["python", "manage.py", "runserver", "0.0.0.0:8000"]
# Clear any command set by the prod compose file (which would be passed
# as an extra argument to manage.py). Setting an empty command prevents
# the image `command` from being appended to the entrypoint.
command: []
volumes:
- ../:/usr/src/app:cached
# Mount the app log directory so logs are visible on the host at ./logs
- ../logs:/var/log/rad
nginx:
# Development nginx override: mount a simplified config that does not
# reference LetsEncrypt certs so the container can start without real
# certificates present on the host.
image: nginx:1.25-alpine
volumes:
- ../deploy/nginx/dev.conf:/etc/nginx/conf.d/default.conf:ro
loki:
image: grafana/loki:2.8.2
command: -config.file=/etc/loki/local-config.yaml
ports:
- "3100:3100"
volumes:
- ./loki-config/local-config.yaml:/etc/loki/local-config.yaml:ro
- ./loki-data:/loki
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://localhost:3100/ready || exit 1"]
interval: 5s
timeout: 3s
retries: 6
promtail:
image: grafana/promtail:2.8.2
volumes:
- ../logs:/var/log/rad:ro
- ./promtail-config.yml:/etc/promtail/promtail-config.yml:ro
command: -config.file=/etc/promtail/promtail-config.yml
depends_on:
- loki
restart: unless-stopped
grafana:
image: grafana/grafana:10.2.0
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
volumes:
- grafana-data:/var/lib/grafana
depends_on:
loki:
condition: service_healthy
restart: unless-stopped
volumes:
grafana-data:
loki-data:
@@ -29,7 +29,7 @@ services:
- 8000:8000
- 3459:3459
env_file:
- ./.env.dev
- ./.env.dev.local
db:
image: postgres:14.2-alpine
volumes:
+119
View File
@@ -0,0 +1,119 @@
services:
redis:
image: redis:7.4.2-alpine
restart: always
volumes:
- redis_data:/data
healthcheck:
test: ["CMD","redis-cli","ping"]
interval: 10s
timeout: 5s
retries: 5
web:
build:
# build context is the repository root (one level up from this file)
context: ..
dockerfile: rad/Dockerfile.prod
restart: always
# Use COMPOSE_ENV to select which env file to load (defaults to 'prod').
# Example: COMPOSE_ENV=dev docker compose -f rad/docker/docker-compose.prod.yml -f rad/docker/docker-compose.dev.yml up -d
env_file:
- ../.env.${COMPOSE_ENV:-prod}
environment:
- DJANGO_SETTINGS_MODULE=rad.settings
depends_on:
redis:
condition: service_healthy
volumes:
- static_volume:/usr/src/app/static
- media_volume:/usr/src/app/media
# Mount the server-specific local settings if present (DO NOT commit secrets).
# On the server create: rad/deploy/settings_local.py and it will be mounted into the container.
- ../deploy/settings_local.py:/usr/src/app/rad/settings_local.py:ro
expose:
- "8000"
command: ["/usr/src/app/entrypoint.sh"]
nginx:
image: nginx:stable-alpine
restart: always
ports:
- "${NGINX_HTTP_PORT:-80}:80"
- "${NGINX_HTTPS_PORT:-443}:443"
depends_on:
- web
volumes:
- ../deploy/nginx/prod.conf:/etc/nginx/conf.d/default.conf:ro
- static_volume:/usr/src/app/static:ro
- media_volume:/usr/src/app/media:ro
- ../deploy/nginx/certs:/etc/letsencrypt:ro
# Host-provided front-end bundles and static folders. Populate these under rad/deploy on the server
- ../deploy/www/viewer:/srv/www/viewer:ro
- ../deploy/www/ohif:/srv/www/ohif:ro
- ../deploy/www/rts:/srv/www/rts:ro
- ../deploy/nicereporter:/srv/nicereporter:rw
- ../deploy/proc-rota:/srv/proc/rota:ro
- ../deploy/uploader:/srv/uploader:ro
healthcheck:
test: ["CMD-SHELL","nginx -t" ]
interval: 30s
timeout: 10s
retries: 3
# Optional local observability stack (can be enabled on servers that
# should run Loki/Grafana). These services use configs found under
# the repository `docker/` directory so the same config works in dev.
loki:
image: grafana/loki:2.8.2
command: -config.file=/etc/loki/local-config.yaml
ports:
- "3100:3100"
volumes:
- ./loki-config/local-config.yaml:/etc/loki/local-config.yaml:ro
- ../docker/loki-data:/loki
# WAL directory: map a host folder so Loki (running as UID 10001)
# can create the write-ahead log. Host folder created under
# `docker/loki-wal` and owned by UID 10001.
- ../docker/loki-wal:/wal
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://localhost:3100/ready || exit 1"]
interval: 10s
timeout: 5s
retries: 6
promtail:
image: grafana/promtail:2.8.2
volumes:
# In prod you may want to point this at the host system log directory.
- ../logs:/var/log/rad:ro
- ./promtail-config.yml:/etc/promtail/promtail-config.yml:ro
command: -config.file=/etc/promtail/promtail-config.yml
depends_on:
- loki
restart: unless-stopped
grafana:
image: grafana/grafana:10.2.0
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
volumes:
- grafana-data:/var/lib/grafana
depends_on:
loki:
condition: service_healthy
restart: unless-stopped
volumes:
postgres_data:
redis_data:
static_volume:
media_volume:
grafana-data:
networks:
default:
driver: bridge
+26
View File
@@ -0,0 +1,26 @@
version: "3.8"
# Local test compose overlay — adds a Postgres service so you can run the
# full stack locally without an external DB. Use it together with
# docker-compose.prod.yml:
#
# docker compose -f rad/docker/docker-compose.prod.yml -f rad/docker/docker-compose.test.yml up -d --build
services:
db:
image: postgres:14-alpine
restart: always
environment:
POSTGRES_USER: ${POSTGRES_USER:-django}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
POSTGRES_DB: ${POSTGRES_DB:-rad}
volumes:
- postgres_test_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL","pg_isready -U ${POSTGRES_USER:-django}" ]
interval: 10s
timeout: 5s
retries: 5
volumes:
postgres_test_data:
+43
View File
@@ -0,0 +1,43 @@
server:
http_listen_port: 3100
grpc_listen_port: 9095
ingester:
lifecycler:
address: 127.0.0.1
ring:
kvstore:
store: inmemory
replication_factor: 1
chunk_idle_period: 5m
chunk_retain_period: 30s
max_transfer_retries: 0
schema_config:
configs:
- from: 2020-10-24
store: boltdb-shipper
object_store: filesystem
schema: v11
index:
prefix: index_
period: 24h
storage_config:
boltdb_shipper:
active_index_directory: /loki/index
cache_location: /loki/cache
shared_store: filesystem
filesystem:
directory: /loki/chunks
# Compactor settings: ensure compactor working directory is inside the mounted
# `/loki` path so the process (running as UID 10001) can create files.
compactor:
working_directory: /loki/compactor
shared_store: filesystem
limits_config:
enforce_metric_name: false
auth_enabled: false
@@ -0,0 +1 @@
{"UID":"f8cade59-3cf9-4ae3-965d-8b0a57007d58","created_at":"2025-12-01T17:14:05.101735276Z","version":{"version":"2.8.2","revision":"9f809eda7","branch":"HEAD","buildUser":"root@e401cfcb874f","buildDate":"2023-05-03T11:07:54Z","goVersion":"go1.20.4"}}
+18
View File
@@ -0,0 +1,18 @@
server:
http_listen_port: 9080
grpc_listen_port: 0
positions:
filename: /tmp/positions.yaml
clients:
- url: http://loki:3100/loki/api/v1/push
scrape_configs:
- job_name: rad_app_logs
static_configs:
- targets:
- localhost
labels:
job: rad_app
__path__: /var/log/rad/*.log
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
set -e
# Lightweight wait-for-postgres using nc (expects DATABASE_HOST and DATABASE_PORT env vars)
if [ -n "${DATABASE_HOST}" ]; then
host="$DATABASE_HOST"
port="${DATABASE_PORT:-5432}"
echo "Waiting for database at ${host}:${port}..."
while ! nc -z "$host" "$port"; do
sleep 1
done
fi
echo "Applying database migrations..."
python manage.py migrate --noinput
echo "Collecting static files..."
python manage.py collectstatic --noinput
echo "Starting gunicorn..."
exec gunicorn rad.wsgi:application \
--name rad_gunicorn \
--bind 0.0.0.0:8000 \
--workers ${GUNICORN_WORKERS:-3} \
--log-level ${GUNICORN_LOGLEVEL:-info}
@@ -44,6 +44,8 @@
Time limit: <strong>{{ exam.time_limit }}</strong> seconds (<span title="Time per question: {% widthratio exam.time_limit question_number 1 %} seconds">per question</span>)
</div>
<div class="mt-2 small text-muted">Author(s): {% for author in exam.author.all %}{{ author }}{% if not forloop.last %}, {% endif %}{% endfor %}</div>
<div class="mt-2">
Exam mode: <strong>{{ exam.exam_mode }}</strong>
{% if exam.exam_mode %}
@@ -178,17 +180,7 @@
</div>
</div>
<div class="row">
<div class="col-12 col-md-6">
{% if exam.examcollection %}
<div class="small">Exam Collection: <a href="{{ exam.examcollection.get_absolute_url }}">{{ exam.examcollection }}</a></div>
{% endif %}
<div class="small mt-1">Author(s): {% for author in exam.author.all %}{{ author }}{% if not forloop.last %}, {% endif %}{% endfor %}</div>
</div>
<div class="col-12 col-md-6 text-md-end small mt-2 mt-md-0">
<span title="If true the results from this exam will be visible to supervisors automatically.">Supervisor visible: {{ exam.results_supervisor_visible }}</span>
</div>
</div>
{# Authors and supervisor visibility moved earlier in the header; duplicate block removed #}
</div>
{% block css %}
+7 -6
View File
@@ -14,19 +14,20 @@ router = Router()
class QuestionSchema(ModelSchema):
class Config:
class Meta:
model = Question
#model_fields = ["question", "history", "feedback", "normal", "laterality"]
model_fields = "__all__"
# Use `fields` per newer ninja ModelSchema API
#fields = ["question", "history", "feedback", "normal", "laterality"]
fields = "__all__"
#model_exclude = ["answers"]
#exclude = ["answers"]
class ExamSchema(ModelSchema):
class Config:
class Meta:
model = Exam
model_fields = ["id", "name", "active", "publish_results"]
fields = ["id", "name", "active", "publish_results"]
@router.get('/')
def list_questions(request):
+6 -6
View File
@@ -15,19 +15,19 @@ router = Router()
class QuestionSchema(ModelSchema):
class Config:
class Meta:
model = Question
#model_fields = ["question", "history", "feedback", "normal", "laterality"]
model_fields = "__all__"
# Use `fields` per newer ninja ModelSchema API
fields = "__all__"
#model_exclude = ["answers"]
#exclude = ["answers"]
class ExamSchema(ModelSchema):
class Config:
class Meta:
model = Exam
model_fields = ["id", "name", "active", "publish_results"]
fields = ["id", "name", "active", "publish_results"]
@router.get('/')
def list_questions(request):
+67 -36
View File
@@ -7,70 +7,101 @@
{% block content %}
{% load thumbnail %}
<div class="physics">
<div class="container physics my-3">
This exam will be available to take <a href="{% url 'physics:exam_start' pk=exam.pk %}">here</a> (when active).
<p class="mb-3">This exam will be available to take <a href="{% url 'physics:exam_start' pk=exam.pk %}">here</a> (when active).</p>
{% autoescape off %}
<ol id="full-question-list-physics">
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0">Questions <small class="text-muted">({{ questions.count }})</small></h5>
<div class="text-muted small">Exam: {{ exam.title }}</div>
</div>
<ul class="list-group list-group-flush" id="full-question-list-physics">
{% for question in questions.all %}
<li class="list-group-item">
<div class="d-flex align-items-start">
<div class="me-3">
<span class="badge bg-secondary">{{ forloop.counter }}</span>
</div>
<div class="flex-grow-1">
<div class="fw-bold mb-2">{{ question.stem|safe }}</div>
<li>
{{ question.stem }}
<ol type="a" class="abcde">
<li class="question-a">
<span class="question-text">{{ question.a }}</span>: <span class="question-answer">{{ question.a_answer }}</span>
<div class="mb-2">
<ol type="a" class="mb-0">
<li class="d-flex justify-content-between align-items-start py-1">
<div><span class="me-2">a)</span><span>{{ question.a }}</span></div>
<div class="text-end">
<div class="text-primary fw-semibold">{{ question.a_answer }}</div>
{% if question.a_feedback %}
<span class="question-feedback">{{question.a_feedback}}</span>
<div class="text-muted small">Feedback: {{ question.a_feedback }}</div>
{% endif %}
</div>
</li>
<li class="question-b">
<span class="question-text">{{ question.b }}</span>: <span class="question-answer">{{ question.b_answer }}</span>
<li class="d-flex justify-content-between align-items-start py-1">
<div><span class="me-2">b)</span><span>{{ question.b }}</span></div>
<div class="text-end">
<div class="text-primary fw-semibold">{{ question.b_answer }}</div>
{% if question.b_feedback %}
<span class="question-feedback">{{question.b_feedback}}</span>
<div class="text-muted small">Feedback: {{ question.b_feedback }}</div>
{% endif %}
</div>
</li>
<li class="question-c">
<span class="question-text">{{ question.c }}</span>: <span class="question-answer">{{ question.c_answer }}</span>
<li class="d-flex justify-content-between align-items-start py-1">
<div><span class="me-2">c)</span><span>{{ question.c }}</span></div>
<div class="text-end">
<div class="text-primary fw-semibold">{{ question.c_answer }}</div>
{% if question.c_feedback %}
<span class="question-feedback">{{question.c_feedback}}</span>
<div class="text-muted small">Feedback: {{ question.c_feedback }}</div>
{% endif %}
</div>
</li>
<li class="question-d">
<span class="question-text">{{ question.d }}</span>: <span class="question-answer">{{ question.d_answer }}</span>
<li class="d-flex justify-content-between align-items-start py-1">
<div><span class="me-2">d)</span><span>{{ question.d }}</span></div>
<div class="text-end">
<div class="text-primary fw-semibold">{{ question.d_answer }}</div>
{% if question.d_feedback %}
<span class="question-feedback">{{question.d_feedback}}</span>
<div class="text-muted small">Feedback: {{ question.d_feedback }}</div>
{% endif %}
</div>
</li>
<li class="question-e">
<span class="question-text">{{ question.e }}</span>: <span class="question-answer">{{ question.e_answer }}</span>
<li class="d-flex justify-content-between align-items-start py-1">
<div><span class="me-2">e)</span><span>{{ question.e }}</span></div>
<div class="text-end">
<div class="text-primary fw-semibold">{{ question.e_answer }}</div>
{% if question.e_feedback %}
<span class="question-feedback">{{question.e_feedback}}</span>
<div class="text-muted small">Feedback: {{ question.e_feedback }}</div>
{% endif %}
</div>
</li>
</ol>
Category: {{ question.category }}, <a href="{% url 'physics:question_detail' pk=question.pk %}">View [id: {{question.pk}}]</a> <a
href="{% url 'admin:physics_question_change' question.id %}">Edit</a>
</div>
<div class="small text-muted">
Category: {{ question.category }}
<a href="{% url 'physics:question_detail' pk=question.pk %}">View</a>
<a href="{% url 'admin:physics_question_change' question.id %}" class="ms-2">Edit</a>
</div>
</div>
</div>
</li>
{% empty %}
<li class="list-group-item text-muted">No questions available.</li>
{% endfor %}
</ol>
{% endautoescape %}
</ul>
</div>
</div>
{% include 'exam_overview_js.html' %}
{% endblock %}
{% block css %}
<style>
.question-answer {
font-weight: bolder;
}
.question-feedback {
opacity: 50%;
float: right
}
.question-feedback::before {
content: "Feedback: ";
}
/* Small visual tweaks on top of Bootstrap */
.question-feedback { opacity: 0.7; }
.list-group-item ol { margin: 0; padding-left: 1.4rem; }
.list-group-item li { list-style-position: inside; }
</style>
{% endblock %}
+15
View File
@@ -0,0 +1,15 @@
{
"folders": [
{
"name": "rad",
"path": "."
}
],
"settings": {
"python.testing.pytestArgs": [
"."
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true
}
}
+79
View File
@@ -0,0 +1,79 @@
FROM python:3.14-slim
# Copy uv helper binary from the uv image so we can manage venvs and pip
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# Install build deps required for common Python packages and netcat for health wait
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
build-essential \
gcc \
git \
libpq-dev \
pkg-config \
libcairo2-dev \
# some distributions provide libgdk-pixbuf under the xlib name
libgdk-pixbuf-xlib-2.0-0 \
libgdk-pixbuf-xlib-2.0-dev \
libjpeg-dev \
zlib1g-dev \
wget \
ca-certificates \
netcat-openbsd \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /usr/src/app
# Install python deps into a uv-managed venv for reproducible builds
COPY requirements.txt /usr/src/app/
# Prebuild wheels into /wheels so compiled artifacts are cached in a layer.
# This speeds rebuilds when `requirements.txt` hasn't changed. The first build
# still needs to compile any packages without prebuilt wheels.
RUN mkdir -p /wheels \
&& python -m venv /tmp/venvbuild \
&& /tmp/venvbuild/bin/pip install --upgrade pip setuptools wheel \
&& /tmp/venvbuild/bin/pip wheel --wheel-dir=/wheels -r requirements.txt \
&& rm -rf /tmp/venvbuild
# Create the final uv-managed venv and install from the cached wheels where
# possible. Using `--no-index --find-links=/wheels` makes pip prefer the
# prebuilt wheels, avoiding recompilation.
RUN uv venv /opt/venv \
&& export VIRTUAL_ENV=/opt/venv \
&& export PATH="/opt/venv/bin:$PATH" \
&& uv pip install --upgrade pip setuptools wheel \
&& uv pip install --no-index --find-links=/wheels -r requirements.txt
# Ensure the runtime environment uses the uv-managed venv by default.
# This persists the venv into image ENV so `python` and `gunicorn` point
# to the venv-installed binaries at container start.
ENV VIRTUAL_ENV=/opt/venv
ENV PATH="/opt/venv/bin:$PATH"
# Create non-root user before copying files so we can use Docker's
# `--chown` flag during COPY and avoid an expensive recursive `chown -R`.
RUN useradd -m appuser
# Create directory for application logs and ensure ownership is correct.
# Do this as root before switching to `appuser` so the directory exists
# and can be mounted by the dev compose override.
RUN mkdir -p /var/log/rad \
&& chown -R appuser:appuser /var/log/rad
# Copy project files into image and set ownership during copy (faster than
# a separate `chown -R` step). This keeps layer reuse efficient.
COPY --chown=appuser:appuser . /usr/src/app
# Ensure the venv is usable by the non-root user; chown only the venv path
# (much smaller than the whole project tree) to avoid a long recursive chown.
RUN chown -R appuser:appuser /opt/venv
# Make the entrypoint executable (some files in the repo may not have the
# executable bit set). Do this as root before switching to the app user.
RUN [ -f /usr/src/app/entrypoint.sh ] && chmod +x /usr/src/app/entrypoint.sh || true
USER appuser
ENTRYPOINT ["/usr/src/app/entrypoint.sh"]
+30
View File
@@ -10,6 +10,36 @@ https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
import os
from django.core.wsgi import get_wsgi_application
from loguru import logger
import sys
from pathlib import Path
# Configure Loguru sinks early so app imports see consistent logging.
# Log to stdout (so `docker logs` shows messages) and to a file at
# `/var/log/rad/app.log` for persistent collection / host tailing.
try:
# ensure directory exists
log_dir = Path("/var/log/rad")
log_dir.mkdir(parents=True, exist_ok=True)
# Add stdout sink (if not already added by other code)
logger.remove() # remove default handlers to avoid duplicate lines
logger.add(sys.stdout, level="INFO", enqueue=True, backtrace=False, diagnose=False)
# Add rotating file sink for persistence in container. Use JSON lines
# (serialize=True) to make logs easy to query in Loki/Grafana.
logger.add(
str(log_dir / "app.log"),
rotation="10 MB",
retention="10 days",
level="DEBUG",
enqueue=True,
serialize=True,
)
except Exception:
# Best-effort only — don't crash WSGI startup if logging can't be configured
try:
logger.add(sys.stderr)
except Exception:
pass
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rad.settings")
+9 -9
View File
@@ -15,19 +15,19 @@ router = Router()
class RapidSchema(ModelSchema):
class Config:
# `ninja` newer versions require an inner `Meta` class instead of `Config`
# for ModelSchema. Replace `Config` with `Meta` to be compatible.
class Meta:
model = Rapid
#model_fields = ["question", "history", "feedback", "normal", "laterality"]
model_fields = "__all__"
#model_exclude = ["answers"]
#model_fields (old API) -> use `fields` per newer ninja ModelSchema API
#fields can be a list of field names or the string "__all__".
#fields = ["question", "history", "feedback", "normal", "laterality"]
fields = "__all__"
class ExamSchema(ModelSchema):
class Config:
class Meta:
model = Exam
model_fields = ["id", "name", "active", "publish_results"]
fields = ["id", "name", "active", "publish_results"]
@router.get('/')
def list_rapids(request):
+5 -6
View File
@@ -15,19 +15,18 @@ router = Router()
class QuestionSchema(ModelSchema):
class Config:
class Meta:
model = Question
#model_fields = ["question", "history", "feedback", "normal", "laterality"]
model_fields = "__all__"
fields = "__all__"
#model_exclude = ["answers"]
#exclude = ["answers"]
class ExamSchema(ModelSchema):
class Config:
class Meta:
model = Exam
model_fields = ["id", "name", "active", "publish_results"]
fields = ["id", "name", "active", "publish_results"]
@router.get('/')
def list_questions(request):
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -e
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"
docker compose -f docker/docker-compose.prod.yml -f docker/docker-compose.test.yml -f docker/docker-compose.dev.yml down --volumes --remove-orphans
+44
View File
@@ -0,0 +1,44 @@
#!/bin/sh
set -e
# Simple local bring-up helper. Usage:
# ./rad/scripts/local-up.sh
# It requires rad/.env.dev to exist (do NOT auto-create from examples) and then
# runs the prod+dev compose stack using COMPOSE_ENV to select the env file.
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"
if [ ! -f .env.dev ]; then
echo ".env.dev not found. Create .env.dev with your development values (pointing to the external dev DB) and re-run."
echo "You can copy .env.prod.example to start from a template, but DO NOT commit secrets."
exit 1
fi
# Default to 'dev' but allow overriding with COMPOSE_ENV environment variable
COMPOSE_ENV=${COMPOSE_ENV:-dev}
echo "Starting compose with COMPOSE_ENV=$COMPOSE_ENV (using .env.$COMPOSE_ENV)"
# Load variables from .env.<env> into the environment so Compose variable
# substitution (e.g. ${NGINX_HTTP_PORT}) works. We export all variables from
# the file for the duration of the command.
ENV_FILE="$REPO_ROOT/.env.$COMPOSE_ENV"
if [ -f "$ENV_FILE" ]; then
# Export variables from the .env file safely without sourcing it. Some
# values include characters (parentheses, ampersands) that break POSIX
# shell parsing if the file is sourced directly. Read line-by-line,
# ignore comments/empty lines and export KEY=VALUE pairs.
while IFS= read -r _line || [ -n "$_line" ]; do
line="$_line"
case "$line" in
''|\#*) continue ;;
esac
# Split on first '=' into key and value
key=${line%%=*}
val=${line#*=}
# Export directly (preserves special characters in the value)
export "$key=$val"
done < "$ENV_FILE"
fi
COMPOSE_ENV=$COMPOSE_ENV docker compose -f docker/docker-compose.prod.yml -f docker/docker-compose.dev.yml up --build
+6 -6
View File
@@ -15,19 +15,19 @@ router = Router()
class QuestionSchema(ModelSchema):
class Config:
class Meta:
model = Question
#model_fields = ["question", "history", "feedback", "normal", "laterality"]
model_fields = "__all__"
# Use `fields` per newer ninja ModelSchema API
fields = "__all__"
#model_exclude = ["answers"]
#exclude = ["answers"]
class ExamSchema(ModelSchema):
class Config:
class Meta:
model = Exam
model_fields = ["id", "name", "active", "publish_results"]
fields = ["id", "name", "active", "publish_results"]
@router.get('/')
def list_questions(request):
+402
View File
@@ -0,0 +1,402 @@
upstream app_server {
server unix:/run/gunicorn.sock fail_timeout=0;
}
server {
#listen 80;
root /home/ross/web/viewer;
#index index.html index.htm;
server_name viewer.penracourses.org.uk;
location / {
#if ($request_method = 'OPTIONS') {
# add_header 'Access-Control-Allow-Origin' * always;
# add_header 'Access-Control-Allow-Credentials' 'true' always;
# add_header 'Access-Control-Allow-Headers' "Origin, X-Requested-With, Content-Type, Accept" always;
# add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
# add_header 'Access-Control-Max-Age' 1728000;
# add_header 'Content-Type' 'text/plain; charset=utf-8';
# add_header 'Content-Length' 0;
# return 204;
#}
#alias /home/ross/web/viewer;
#add_header Cross-Origin-Opener-Policy same-origin;
#add_header Cross-Origin-Embedder-Policy require-corp;
#add_header 'Cross-Origin-Opener-Policy' 'cross-origin' always;
#add_header 'Cross-Origin-Embedder-Policy' 'credentialless' always;
index index.html;
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-store, no-cache, must-revalidate";
add_header 'Cross-Origin-Resource-Policy' 'cross-origin';
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/viewer.penracourses.org.uk/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/viewer.penracourses.org.uk/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
listen 80;
server_name penracourses.org.uk;
return 301 https://www.penracourses.org.uk$request_uri;
}
server {
listen [::]:443 ssl; # managed by Certbot
server_name penracourses.org.uk;
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/penracourses.org.uk/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/penracourses.org.uk/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
return 301 https://www.penracourses.org.uk$request_uri;
}
server {
#listen 80;
root /usr/share/nginx/html;
index index.html index.htm;
client_max_body_size 4G;
#server_name _;
server_name www.penracourses.org.uk;
resolver 127.0.0.11;
keepalive_timeout 20;
set $cors "";
if ($http_origin ~* (https?://(localhost:5173|viewer\.penracourses\.org\.uk))) {
set $cors $http_origin;
}
# Your Django project's media files - amend as required
location /media {
if ($request_method = OPTIONS ) {
add_header 'Access-Control-Allow-Origin' $cors always;
#add_header 'Access-Control-Allow-Origin' 'https://viewer.penracourses.org.uk' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Headers' "Origin, X-Requested-With, Content-Type, Accept" always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 200;
}
#add_header 'Access-Control-Allow-Origin' 'https://viewer.penracourses.org.uk' always;
add_header 'Access-Control-Allow-Origin' $cors always;
alias /home/ross/web/rad/media;
#add_header Access-Control-Allow-Origin *;
#add_header Access-Control-Allow-Origin http://localhost:8000;
#add_header Vary Origin;
}
# your Django project's static files - amend as required
location /static {
alias /home/ross/web/static;
}
# rts
location /rts {
alias /home/ross/web/rts;
}
# OHIF
location /viewer {
#add_header 'Cross-Origin-Opener-Policy' 'cross-origin' always;
#add_header 'Cross-Origin-Embedder-Policy' 'credentialless' always;
#add_header 'Cross-Origin-Resource-Policy' 'cross-origin' always;
alias /home/ross/web/viewer;
}
location /ohif {
add_header 'Cross-Origin-Opener-Policy' 'same-origin' always;
add_header 'Cross-Origin-Embedder-Policy' 'require-corp' always;
add_header 'Cross-Origin-Resource-Policy' 'same-site' always;
alias /home/ross/web/ohif;
try_files $uri /ohif/index.html;
#autoindex on;
}
# # Proxy the static assests for the Django Admin panel
# location /static/admin {
# alias /usr/lib/python3/dist-packages/django/contrib/admin/static/admin/;
# }
location /rota {
alias /home/ross/proc/proc-rota;
autoindex on;
}
location /uploader {
alias /home/ross/uploader;
autoindex on;
}
location ~ ^/reporter/(.*)$ {
alias /home/ross/web/nicereporter;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Authorization $http_authorization;
proxy_pass_header Authorization;
proxy_pass http://127.0.0.1:5129/$1?$args;
proxy_set_header X-Forwarded-Prefix /reporter;
proxy_redirect http://127.0.0.1:5129/ /reporter/;
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
proxy_redirect off;
proxy_buffering off;
#add_header 'Cross-Origin-Opener-Policy' 'single-origin' always;
#add_header 'Cross-Origin-Embedder-Policy' 'require-corp' always;
#add_header 'Cross-Origin-Resource-Policy' 'same-site' always;
#add_header 'Cross-Origin-Opener-Policy' 'same-origin' always;
add_header 'Cross-Origin-Embedder-Policy' 'require-corp' always;
add_header 'Cross-Origin-Resource-Policy' 'same-site' always;
#add_header 'Access-Control-Allow-Origin' $cors always;
proxy_pass http://app_server;
#add_header Access-Control-Allow-Origin *;
#add_header Vary Origin;
}
#location ~* \.(jpg|jpeg|png|dicom)$ {
# add_header Access-Control-Allow-Origin *;
#}
# rota
listen [::]:443 ssl; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/penracourses.org.uk/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/penracourses.org.uk/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
#server {
#server_name 161.35.163.87;
#add_header X-Frame-Options "SAMEORIGIN";
#
#return 301 $scheme://penracourses.org.uk$request_uri;
#}
#server {
# #listen 80;
# #server_name penracoureses.org.uk www.penracourses.org.uk;
#
# root /usr/share/nginx/html;
# index index.html index.htm;
#
# client_max_body_size 4G;
# #server_name _;
# server_name penracourses.org.uk; # managed by Certbot
#
# keepalive_timeout 5;
#
# # Your Django project's media files - amend as required
# location /media {
# alias /home/ross/web/rad/media;
# #add_header Access-Control-Allow-Origin *;
# #add_header Access-Control-Allow-Origin http://localhost:8000;
# #add_header Vary Origin;
# }
#
# # your Django project's static files - amend as required
# location /static {
# alias /home/ross/web/rad/static;
# }
#
# # rts
# location /rts {
# alias /home/ross/web/rts;
# }
#
# # # Proxy the static assests for the Django Admin panel
# # location /static/admin {
# # alias /usr/lib/python3/dist-packages/django/contrib/admin/static/admin/;
# # }
#
# location / {
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_set_header Host $host;
# proxy_redirect off;
# proxy_buffering off;
#
# proxy_pass http://app_server;
# }
#
# #location ~* \.(jpg|jpeg|png|dicom)$ {
# # add_header Access-Control-Allow-Origin *;
# #}
#
# # rota
# location /rota {
# alias /home/ross/proc-rota;
# }
#
# location /rota2 {
# alias /home/ross/neos;
# }
#
#
#
#
#
# listen [::]:443 ssl ipv6only=on; # managed by Certbot
# listen 443 ssl; # managed by Certbot
# ssl_certificate /etc/letsencrypt/live/penracourses.org.uk/fullchain.pem; # managed by Certbot
# ssl_certificate_key /etc/letsencrypt/live/penracourses.org.uk/privkey.pem; # managed by Certbot
# include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
# ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
#
#}
server {
root /home/ross/web/rts;
index index.html index.htm;
client_max_body_size 4G;
#server_name _;
server_name dev.penracourses.org.uk www.dev.penracourses.org.uk;
keepalive_timeout 5;
# Your Django project's media files - amend as required
location /media {
# Simple requests
if ($request_method ~* "(GET|POST)") {
add_header "Access-Control-Allow-Origin" *;
}
# Preflighted requests
if ($request_method = OPTIONS ) {
add_header "Access-Control-Allow-Origin" *;
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
return 200;
}
alias /home/ross/web/rad/media;
#add_header Access-Control-Allow-Origin *;
#add_header Access-Control-Allow-Origin http://localhost:8000;
#add_header Vary Origin;
}
# your Django project's static files - amend as required
location /static {
alias /home/ross/web/rad/static;
}
# rts
location /rts {
alias /home/ross/web/rts;
}
# # Proxy the static assests for the Django Admin panel
# location /static/admin {
# alias /usr/lib/python3/dist-packages/django/contrib/admin/static/admin/;
# }
location / {
add_header 'Access-Control-Allow-Origin' '*' always;
try_files $uri $uri/ =404;
#proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#proxy_set_header X-Forwarded-Proto $scheme;
#proxy_set_header Host $host;
#proxy_redirect off;
#proxy_buffering off;
#proxy_pass http://app_server;
#add_header Access-Control-Allow-Origin *;
#add_header Vary Origin;
}
#location ~* \.(jpg|jpeg|png|dicom)$ {
# add_header Access-Control-Allow-Origin *;
#}
#listen [::]:443 ssl; # managed by Certbot
#listen 443 ssl; # managed by Certbot
#ssl_certificate /etc/letsencrypt/live/penracourses.org.uk/fullchain.pem; # managed by Certbot
#ssl_certificate_key /etc/letsencrypt/live/penracourses.org.uk/privkey.pem; # managed by Certbot
#include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
#ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = penracourses.org.uk) {
return 301 https://www.$host$request_uri;
} # managed by Certbot
listen 80 ;
listen [::]:80 ;
server_name penracourses.org.uk;
return 404; # managed by Certbot
}
server {
if ($host = www.penracourses.org.uk) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
server_name www.penracourses.org.uk;
return 404; # managed by Certbot
}
server {
if ($host = viewer.penracourses.org.uk) {
return 301 https://$host$request_uri;
} # managed by Certbot
server_name viewer.penracourses.org.uk;
listen 80;
return 404; # managed by Certbot
}
+54
View File
@@ -0,0 +1,54 @@
DEBUG = False
INTERNAL_IPS = ["82.69.88.125", "217.155.198.96"]
#SECURE_SSL_REDIRECT = False
#SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'http')
#REMOTE_URL = "http://46.101.13.46:8123"
#
#MEDIA_ROOT = '/home/django/rad/media/'
STATIC_ROOT = '/home/ross/web/static/'
#EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
if not DEBUG:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'log.txt',
'formatter': 'verbose'
},
},
'loggers': {
'django': {
'handlers':['file'],
'propagate': True,
'level':'DEBUG',
},
'atlas': {
'handlers': ['file'],
'level': 'DEBUG',
},
#"django.core.mail": {"handlers": ["console"], "level": "DEBUG", "propagate": False},
#"smtplib": {"handlers": ["console"], "level": "DEBUG", "propagate": False},
}
}
CIMAR_USERNAME = "ross.kruger@nhs.net"
CIMAR_PASSWORD = "[prdr32@cimar]"
# Celery settings
CELERY_BROKER_URL = "redis://localhost:6379"
CELERY_RESULT_BACKEND = "redis://localhost:6379"