prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  RawImageFileAdmin has incorrect relation defined
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `app/grandchallenge/cases/admin.py`
  Content:
  ```
  1 import re
  2 from functools import update_wrapper
  3 
  4 from django.contrib import admin
  5 from django.contrib.admin.utils import unquote
  6 from django.core.exceptions import PermissionDenied
  7 from django.http import Http404, HttpResponse
  8 from django.urls import path
  9 from django.utils.html import format_html
  10 from guardian.admin import GuardedModelAdmin
  11 
  12 from grandchallenge.cases.models import (
  13     Image,
  14     ImageFile,
  15     RawImageFile,
  16     RawImageUploadSession,
  17 )
  18 from grandchallenge.jqfileupload.widgets.uploader import StagedAjaxFile
  19 from grandchallenge.subdomains.utils import reverse
  20 
  21 
  22 class ImageFileInline(admin.StackedInline):
  23     model = ImageFile
  24     extra = 0
  25 
  26 
  27 class ImageAdmin(GuardedModelAdmin):
  28     search_fields = (
  29         "pk",
  30         "name",
  31         "study__name",
  32         "modality__modality",
  33         "color_space",
  34         "eye_choice",
  35         "field_of_view",
  36         "stereoscopic_choice",
  37         "study__patient__name",
  38     )
  39     list_filter = (
  40         "modality",
  41         "color_space",
  42         "eye_choice",
  43         "field_of_view",
  44         "stereoscopic_choice",
  45         "archive__slug",
  46     )
  47     inlines = [ImageFileInline]
  48     readonly_fields = ("origin",)
  49 
  50 
  51 class ImageInline(admin.StackedInline):
  52     model = Image
  53     extra = 0
  54 
  55 
  56 class MhdOrRawFilter(admin.SimpleListFilter):
  57     """Allow filtering on mhd or raw/zraw files."""
  58 
  59     title = "MHD or RAW file"
  60     parameter_name = "mhd_or_raw"
  61 
  62     def lookups(self, request, model_admin):
  63         return (("mhd", "MHD file"), ("raw", "RAW/ZRAW file"))
  64 
  65     def queryset(self, request, queryset):
  66         if self.value() == "mhd":
  67             return queryset.filter(file__endswith=".mhd")
  68         if self.value() == "raw":
  69             return queryset.filter(file__endswith="raw")
  70 
  71 
  72 class ImageFileAdmin(GuardedModelAdmin):
  73     search_fields = ("pk", "file", "image__name")
  74     list_filter = (MhdOrRawFilter,)
  75     readonly_fields = ("image",)
  76 
  77 
  78 class RawImageUploadSessionAdmin(GuardedModelAdmin):
  79     ordering = ("-created",)
  80     list_display = (
  81         "pk",
  82         "created",
  83         "creator",
  84         "status",
  85         "error_message",
  86     )
  87     readonly_fields = (
  88         "creator",
  89         "status",
  90     )
  91     list_filter = ("status",)
  92     search_fields = (
  93         "creator__username",
  94         "pk",
  95         "error_message",
  96     )
  97 
  98 
  99 class DownloadableFilter(admin.SimpleListFilter):
  100     """Allow filtering on downloadable files."""
  101 
  102     title = "Downloadable"
  103     parameter_name = "downloadable"
  104 
  105     def lookups(self, request, model_admin):
  106         return (("yes", "Yes"),)
  107 
  108     def queryset(self, request, queryset):
  109         if self.value() == "yes":
  110             return queryset.filter(staged_file_id__isnull=False)
  111         return queryset
  112 
  113 
  114 class RawImageFileAdmin(GuardedModelAdmin):
  115     list_filter = (DownloadableFilter,)
  116     list_display = ("filename", "upload_session", "download")
  117     list_select_related = ("upload_session__archive",)
  118     readonly_fields = (
  119         "download",
  120         "upload_session",
  121     )
  122     search_fields = ("upload_session__pk", "filename")
  123 
  124     def download(self, instance):
  125         if not instance.staged_file_id:
  126             return
  127         return format_html(
  128             f'<a class="button" href={reverse(f"admin:{self.model._meta.app_label}_{self.model._meta.model_name}_download", kwargs={"object_id": instance.pk})}>Download</a>'
  129         )
  130 
  131     def download_view(self, request, object_id, **kwargs):
  132         obj = self.get_object(request, unquote(object_id), None)
  133         if not self.has_view_or_change_permission(request, obj):
  134             raise PermissionDenied
  135 
  136         try:
  137             saf = StagedAjaxFile(obj.staged_file_id).open()
  138             response = HttpResponse(
  139                 saf.read(), content_type="application/dicom"
  140             )
  141             response[
  142                 "Content-Disposition"
  143             ] = f'attachment; filename="{obj.filename}"'
  144             return response
  145         except Exception:
  146             raise Http404("File not found")
  147 
  148     def get_urls(self):
  149         def wrap(view):
  150             def wrapper(*args, **kwargs):
  151                 return self.admin_site.admin_view(view)(*args, **kwargs)
  152 
  153             wrapper.model_admin = self
  154             return update_wrapper(wrapper, view)
  155 
  156         urls = super().get_urls()
  157 
  158         download_url = path(
  159             "<path:object_id>/download/",
  160             wrap(self.download_view),
  161             name=f"{self.model._meta.app_label}_{self.model._meta.model_name}_download",
  162         )
  163         # Currently the last url in ModelAdmin's get-urls is this:
  164         # # For backwards compatibility (was the change url before 1.9)
  165         #   path('<path:object_id>/', wrap(RedirectView.as_view(
  166         #       pattern_name='%s:%s_%s_change' % ((self.admin_site.name,) + info)
  167         #   ))),
  168         # This would also match <path:object_id>/download/ and is only there for
  169         # old django versions, which we do not use. Replace it if it is there.
  170         # Otherwise just append the download_url to the list.
  171         if urls[-1].pattern.regex == re.compile("^(?P<object_id>.+)/$"):
  172             urls[-1] = download_url
  173         else:
  174             urls.append(download_url)
  175 
  176         return urls
  177 
  178 
  179 admin.site.register(Image, ImageAdmin)
  180 admin.site.register(ImageFile, ImageFileAdmin)
  181 admin.site.register(RawImageUploadSession, RawImageUploadSessionAdmin)
  182 admin.site.register(RawImageFile, RawImageFileAdmin)
  183
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/app/grandchallenge/cases/admin.py b/app/grandchallenge/cases/admin.py
  --- a/app/grandchallenge/cases/admin.py
  +++ b/app/grandchallenge/cases/admin.py
  @@ -114,7 +114,6 @@
   class RawImageFileAdmin(GuardedModelAdmin):
       list_filter = (DownloadableFilter,)
       list_display = ("filename", "upload_session", "download")
  -    list_select_related = ("upload_session__archive",)
       readonly_fields = (
           "download",
           "upload_session",
  
verification_info: {"golden_diff": "diff --git a/app/grandchallenge/cases/admin.py b/app/grandchallenge/cases/admin.py\n--- a/app/grandchallenge/cases/admin.py\n+++ b/app/grandchallenge/cases/admin.py\n@@ -114,7 +114,6 @@\n class RawImageFileAdmin(GuardedModelAdmin):\n     list_filter = (DownloadableFilter,)\n     list_display = (\"filename\", \"upload_session\", \"download\")\n-    list_select_related = (\"upload_session__archive\",)\n     readonly_fields = (\n         \"download\",\n         \"upload_session\",\n", "issue": "RawImageFileAdmin has incorrect relation defined\n\n", "before_files": [{"content": "import re\nfrom functools import update_wrapper\n\nfrom django.contrib import admin\nfrom django.contrib.admin.utils import unquote\nfrom django.core.exceptions import PermissionDenied\nfrom django.http import Http404, HttpResponse\nfrom django.urls import path\nfrom django.utils.html import format_html\nfrom guardian.admin import GuardedModelAdmin\n\nfrom grandchallenge.cases.models import (\n    Image,\n    ImageFile,\n    RawImageFile,\n    RawImageUploadSession,\n)\nfrom grandchallenge.jqfileupload.widgets.uploader import StagedAjaxFile\nfrom grandchallenge.subdomains.utils import reverse\n\n\nclass ImageFileInline(admin.StackedInline):\n    model = ImageFile\n    extra = 0\n\n\nclass ImageAdmin(GuardedModelAdmin):\n    search_fields = (\n        \"pk\",\n        \"name\",\n        \"study__name\",\n        \"modality__modality\",\n        \"color_space\",\n        \"eye_choice\",\n        \"field_of_view\",\n        \"stereoscopic_choice\",\n        \"study__patient__name\",\n    )\n    list_filter = (\n        \"modality\",\n        \"color_space\",\n        \"eye_choice\",\n        \"field_of_view\",\n        \"stereoscopic_choice\",\n        \"archive__slug\",\n    )\n    inlines = [ImageFileInline]\n    readonly_fields = (\"origin\",)\n\n\nclass ImageInline(admin.StackedInline):\n    model = Image\n    extra = 0\n\n\nclass MhdOrRawFilter(admin.SimpleListFilter):\n    \"\"\"Allow filtering on mhd or raw/zraw files.\"\"\"\n\n    title = \"MHD or RAW file\"\n    parameter_name = \"mhd_or_raw\"\n\n    def lookups(self, request, model_admin):\n        return ((\"mhd\", \"MHD file\"), (\"raw\", \"RAW/ZRAW file\"))\n\n    def queryset(self, request, queryset):\n        if self.value() == \"mhd\":\n            return queryset.filter(file__endswith=\".mhd\")\n        if self.value() == \"raw\":\n            return queryset.filter(file__endswith=\"raw\")\n\n\nclass ImageFileAdmin(GuardedModelAdmin):\n    search_fields = (\"pk\", \"file\", \"image__name\")\n    list_filter = (MhdOrRawFilter,)\n    readonly_fields = (\"image\",)\n\n\nclass RawImageUploadSessionAdmin(GuardedModelAdmin):\n    ordering = (\"-created\",)\n    list_display = (\n        \"pk\",\n        \"created\",\n        \"creator\",\n        \"status\",\n        \"error_message\",\n    )\n    readonly_fields = (\n        \"creator\",\n        \"status\",\n    )\n    list_filter = (\"status\",)\n    search_fields = (\n        \"creator__username\",\n        \"pk\",\n        \"error_message\",\n    )\n\n\nclass DownloadableFilter(admin.SimpleListFilter):\n    \"\"\"Allow filtering on downloadable files.\"\"\"\n\n    title = \"Downloadable\"\n    parameter_name = \"downloadable\"\n\n    def lookups(self, request, model_admin):\n        return ((\"yes\", \"Yes\"),)\n\n    def queryset(self, request, queryset):\n        if self.value() == \"yes\":\n            return queryset.filter(staged_file_id__isnull=False)\n        return queryset\n\n\nclass RawImageFileAdmin(GuardedModelAdmin):\n    list_filter = (DownloadableFilter,)\n    list_display = (\"filename\", \"upload_session\", \"download\")\n    list_select_related = (\"upload_session__archive\",)\n    readonly_fields = (\n        \"download\",\n        \"upload_session\",\n    )\n    search_fields = (\"upload_session__pk\", \"filename\")\n\n    def download(self, instance):\n        if not instance.staged_file_id:\n            return\n        return format_html(\n            f'<a class=\"button\" href={reverse(f\"admin:{self.model._meta.app_label}_{self.model._meta.model_name}_download\", kwargs={\"object_id\": instance.pk})}>Download</a>'\n        )\n\n    def download_view(self, request, object_id, **kwargs):\n        obj = self.get_object(request, unquote(object_id), None)\n        if not self.has_view_or_change_permission(request, obj):\n            raise PermissionDenied\n\n        try:\n            saf = StagedAjaxFile(obj.staged_file_id).open()\n            response = HttpResponse(\n                saf.read(), content_type=\"application/dicom\"\n            )\n            response[\n                \"Content-Disposition\"\n            ] = f'attachment; filename=\"{obj.filename}\"'\n            return response\n        except Exception:\n            raise Http404(\"File not found\")\n\n    def get_urls(self):\n        def wrap(view):\n            def wrapper(*args, **kwargs):\n                return self.admin_site.admin_view(view)(*args, **kwargs)\n\n            wrapper.model_admin = self\n            return update_wrapper(wrapper, view)\n\n        urls = super().get_urls()\n\n        download_url = path(\n            \"<path:object_id>/download/\",\n            wrap(self.download_view),\n            name=f\"{self.model._meta.app_label}_{self.model._meta.model_name}_download\",\n        )\n        # Currently the last url in ModelAdmin's get-urls is this:\n        # # For backwards compatibility (was the change url before 1.9)\n        #   path('<path:object_id>/', wrap(RedirectView.as_view(\n        #       pattern_name='%s:%s_%s_change' % ((self.admin_site.name,) + info)\n        #   ))),\n        # This would also match <path:object_id>/download/ and is only there for\n        # old django versions, which we do not use. Replace it if it is there.\n        # Otherwise just append the download_url to the list.\n        if urls[-1].pattern.regex == re.compile(\"^(?P<object_id>.+)/$\"):\n            urls[-1] = download_url\n        else:\n            urls.append(download_url)\n\n        return urls\n\n\nadmin.site.register(Image, ImageAdmin)\nadmin.site.register(ImageFile, ImageFileAdmin)\nadmin.site.register(RawImageUploadSession, RawImageUploadSessionAdmin)\nadmin.site.register(RawImageFile, RawImageFileAdmin)\n", "path": "app/grandchallenge/cases/admin.py"}], "after_files": [{"content": "import re\nfrom functools import update_wrapper\n\nfrom django.contrib import admin\nfrom django.contrib.admin.utils import unquote\nfrom django.core.exceptions import PermissionDenied\nfrom django.http import Http404, HttpResponse\nfrom django.urls import path\nfrom django.utils.html import format_html\nfrom guardian.admin import GuardedModelAdmin\n\nfrom grandchallenge.cases.models import (\n    Image,\n    ImageFile,\n    RawImageFile,\n    RawImageUploadSession,\n)\nfrom grandchallenge.jqfileupload.widgets.uploader import StagedAjaxFile\nfrom grandchallenge.subdomains.utils import reverse\n\n\nclass ImageFileInline(admin.StackedInline):\n    model = ImageFile\n    extra = 0\n\n\nclass ImageAdmin(GuardedModelAdmin):\n    search_fields = (\n        \"pk\",\n        \"name\",\n        \"study__name\",\n        \"modality__modality\",\n        \"color_space\",\n        \"eye_choice\",\n        \"field_of_view\",\n        \"stereoscopic_choice\",\n        \"study__patient__name\",\n    )\n    list_filter = (\n        \"modality\",\n        \"color_space\",\n        \"eye_choice\",\n        \"field_of_view\",\n        \"stereoscopic_choice\",\n        \"archive__slug\",\n    )\n    inlines = [ImageFileInline]\n    readonly_fields = (\"origin\",)\n\n\nclass ImageInline(admin.StackedInline):\n    model = Image\n    extra = 0\n\n\nclass MhdOrRawFilter(admin.SimpleListFilter):\n    \"\"\"Allow filtering on mhd or raw/zraw files.\"\"\"\n\n    title = \"MHD or RAW file\"\n    parameter_name = \"mhd_or_raw\"\n\n    def lookups(self, request, model_admin):\n        return ((\"mhd\", \"MHD file\"), (\"raw\", \"RAW/ZRAW file\"))\n\n    def queryset(self, request, queryset):\n        if self.value() == \"mhd\":\n            return queryset.filter(file__endswith=\".mhd\")\n        if self.value() == \"raw\":\n            return queryset.filter(file__endswith=\"raw\")\n\n\nclass ImageFileAdmin(GuardedModelAdmin):\n    search_fields = (\"pk\", \"file\", \"image__name\")\n    list_filter = (MhdOrRawFilter,)\n    readonly_fields = (\"image\",)\n\n\nclass RawImageUploadSessionAdmin(GuardedModelAdmin):\n    ordering = (\"-created\",)\n    list_display = (\n        \"pk\",\n        \"created\",\n        \"creator\",\n        \"status\",\n        \"error_message\",\n    )\n    readonly_fields = (\n        \"creator\",\n        \"status\",\n    )\n    list_filter = (\"status\",)\n    search_fields = (\n        \"creator__username\",\n        \"pk\",\n        \"error_message\",\n    )\n\n\nclass DownloadableFilter(admin.SimpleListFilter):\n    \"\"\"Allow filtering on downloadable files.\"\"\"\n\n    title = \"Downloadable\"\n    parameter_name = \"downloadable\"\n\n    def lookups(self, request, model_admin):\n        return ((\"yes\", \"Yes\"),)\n\n    def queryset(self, request, queryset):\n        if self.value() == \"yes\":\n            return queryset.filter(staged_file_id__isnull=False)\n        return queryset\n\n\nclass RawImageFileAdmin(GuardedModelAdmin):\n    list_filter = (DownloadableFilter,)\n    list_display = (\"filename\", \"upload_session\", \"download\")\n    readonly_fields = (\n        \"download\",\n        \"upload_session\",\n    )\n    search_fields = (\"upload_session__pk\", \"filename\")\n\n    def download(self, instance):\n        if not instance.staged_file_id:\n            return\n        return format_html(\n            f'<a class=\"button\" href={reverse(f\"admin:{self.model._meta.app_label}_{self.model._meta.model_name}_download\", kwargs={\"object_id\": instance.pk})}>Download</a>'\n        )\n\n    def download_view(self, request, object_id, **kwargs):\n        obj = self.get_object(request, unquote(object_id), None)\n        if not self.has_view_or_change_permission(request, obj):\n            raise PermissionDenied\n\n        try:\n            saf = StagedAjaxFile(obj.staged_file_id).open()\n            response = HttpResponse(\n                saf.read(), content_type=\"application/dicom\"\n            )\n            response[\n                \"Content-Disposition\"\n            ] = f'attachment; filename=\"{obj.filename}\"'\n            return response\n        except Exception:\n            raise Http404(\"File not found\")\n\n    def get_urls(self):\n        def wrap(view):\n            def wrapper(*args, **kwargs):\n                return self.admin_site.admin_view(view)(*args, **kwargs)\n\n            wrapper.model_admin = self\n            return update_wrapper(wrapper, view)\n\n        urls = super().get_urls()\n\n        download_url = path(\n            \"<path:object_id>/download/\",\n            wrap(self.download_view),\n            name=f\"{self.model._meta.app_label}_{self.model._meta.model_name}_download\",\n        )\n        # Currently the last url in ModelAdmin's get-urls is this:\n        # # For backwards compatibility (was the change url before 1.9)\n        #   path('<path:object_id>/', wrap(RedirectView.as_view(\n        #       pattern_name='%s:%s_%s_change' % ((self.admin_site.name,) + info)\n        #   ))),\n        # This would also match <path:object_id>/download/ and is only there for\n        # old django versions, which we do not use. Replace it if it is there.\n        # Otherwise just append the download_url to the list.\n        if urls[-1].pattern.regex == re.compile(\"^(?P<object_id>.+)/$\"):\n            urls[-1] = download_url\n        else:\n            urls.append(download_url)\n\n        return urls\n\n\nadmin.site.register(Image, ImageAdmin)\nadmin.site.register(ImageFile, ImageFileAdmin)\nadmin.site.register(RawImageUploadSession, RawImageUploadSessionAdmin)\nadmin.site.register(RawImageFile, RawImageFileAdmin)\n", "path": "app/grandchallenge/cases/admin.py"}]}