We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
`UnboundLocalError` in imprint form
### Describe the Bug
<!-- A clear and concise description of what the bug is. -->
The imprint can only be created when it does not yet exist.
Once it exists, it cannot be changed anymore.

### Steps to Reproduce

1. Go to the imprint form
2. Create imprint
3. Change existing imprint translation
4. See error

### Expected Behavior
<!-- A clear and concise description of what you expected to happen. -->
The imprint translation should be changed

### Actual Behavior
<!-- A clear and concise description of what actually happened. -->
`UnboundLocalError at /augsburg/imprint/de/`
`local variable 'imprint' referenced before assignment`
### Additional Information
<!-- Add any other context (e.g. logs, screenshots, etc.) about the problem here. -->

<details>
 <summary>Traceback</summary>

```
Environment:


Request Method: POST
Request URL: http://localhost:8000/augsburg/imprint/de/

Django Version: 3.2.2
Python Version: 3.7.10
Installed Applications:
['cms.apps.CmsConfig',
 'gvz_api.apps.GvzApiConfig',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.messages',
 'django.contrib.sessions',
 'django.contrib.sitemaps',
 'django.contrib.staticfiles',
 'corsheaders',
 'widget_tweaks',
 'easy_thumbnails',
 'filer',
 'mptt',
 'rules.apps.AutodiscoverRulesConfig',
 'linkcheck',
 'django.contrib.admin']
Installed Middleware:
['corsheaders.middleware.CorsMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'cms.middleware.timezone_middleware.TimezoneMiddleware']

Traceback (most recent call last):
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/src/cms/decorators.py", line 53, in wrap
    return function(request, *args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 104, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/views/generic/base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/src/cms/views/imprint/imprint_view.py", line 226, in post
    imprint=imprint,

Exception Type: UnboundLocalError at /augsburg/imprint/de/
Exception Value: local variable 'imprint' referenced before assignment
```

</details>

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/cms/views/imprint/imprint_view.py`
Content:
```
1 import logging
2 
3 from django.contrib import messages
4 from django.contrib.auth.decorators import login_required
5 from django.contrib.auth.mixins import PermissionRequiredMixin
6 from django.shortcuts import render, redirect, get_object_or_404
7 from django.urls import reverse
8 from django.utils.decorators import method_decorator
9 from django.utils.translation import ugettext as _
10 from django.views.generic import TemplateView
11 
12 from backend.settings import IMPRINT_SLUG, WEBAPP_URL
13 from ...constants import status
14 from ...decorators import region_permission_required
15 from ...forms import ImprintTranslationForm
16 from ...models import ImprintPageTranslation, ImprintPage, Region
17 
18 logger = logging.getLogger(__name__)
19 
20 
21 @method_decorator(login_required, name="dispatch")
22 @method_decorator(region_permission_required, name="dispatch")
23 class ImprintView(PermissionRequiredMixin, TemplateView):
24     """
25     View for the imprint page form and imprint page translation form
26     """
27 
28     permission_required = "cms.manage_imprint"
29     raise_exception = True
30 
31     template_name = "imprint/imprint_form.html"
32     base_context = {
33         "current_menu_item": "imprint",
34         "WEBAPP_URL": WEBAPP_URL,
35         "IMPRINT_SLUG": IMPRINT_SLUG,
36     }
37 
38     def get(self, request, *args, **kwargs):
39         """
40         Render :class:`~cms.forms.imprint.imprint_translation_form.ImprintTranslationForm`
41 
42         :param request: The current request
43         :type request: ~django.http.HttpResponse
44 
45         :param args: The supplied arguments
46         :type args: list
47 
48         :param kwargs: The supplied keyword arguments
49         :type kwargs: dict
50 
51         :raises ~django.core.exceptions.PermissionDenied: If user does not have the permission to edit the specific page
52 
53         :return: The rendered template response
54         :rtype: ~django.template.response.TemplateResponse
55         """
56 
57         # current region
58         region = Region.get_current_region(request)
59 
60         # current language
61         language_slug = kwargs.get("language_slug")
62         if language_slug:
63             language = get_object_or_404(region.languages, slug=language_slug)
64         elif region.default_language:
65             return redirect(
66                 "edit_imprint",
67                 **{
68                     "region_slug": region.slug,
69                     "language_slug": region.default_language.slug,
70                 },
71             )
72         else:
73             messages.error(
74                 request,
75                 _("Please create at least one language node before creating pages."),
76             )
77             return redirect(
78                 "language_tree",
79                 **{
80                     "region_slug": region.slug,
81                 },
82             )
83 
84         # get imprint and translation objects if they exist
85         try:
86             imprint = region.imprint
87         except ImprintPage.DoesNotExist:
88             imprint = None
89 
90         imprint_translation = ImprintPageTranslation.objects.filter(
91             page=imprint,
92             language=language,
93         ).first()
94 
95         # Make form disabled if user has no permission to manage the imprint
96         disabled = False
97         if imprint:
98             if imprint.archived:
99                 disabled = True
100                 messages.warning(
101                     request, _("You cannot manage the imprint because it is archived.")
102                 )
103             public_translation = imprint.get_public_translation(language.slug)
104             if public_translation and imprint_translation != public_translation:
105                 messages.info(
106                     request,
107                     _(
108                         "This is <b>not</b> the most recent public revision of this translation. Instead, <a href='%(revision_url)s' class='underline hover:no-underline'>revision %(revision)s</a> is shown in the apps."
109                     )
110                     % {
111                         "revision_url": reverse(
112                             "imprint_revisions",
113                             kwargs={
114                                 "region_slug": region.slug,
115                                 "language_slug": language.slug,
116                                 "selected_revision": public_translation.version,
117                             },
118                         ),
119                         "revision": public_translation.version,
120                     },
121                 )
122 
123         imprint_translation_form = ImprintTranslationForm(
124             instance=imprint_translation, disabled=disabled
125         )
126 
127         # Pass side by side language options
128         side_by_side_language_options = self.get_side_by_side_language_options(
129             region, language, imprint
130         )
131 
132         return render(
133             request,
134             self.template_name,
135             {
136                 **self.base_context,
137                 "imprint_translation_form": imprint_translation_form,
138                 "imprint": imprint,
139                 "language": language,
140                 # Languages for tab view
141                 "languages": region.languages if imprint else [language],
142                 "side_by_side_language_options": side_by_side_language_options,
143             },
144         )
145 
146     # pylint: disable=too-many-branches,unused-argument
147     def post(self, request, *args, **kwargs):
148         """
149         Binds the user input data to the imprint form and validates the input.
150         Forms containing images/files need to be additionally instantiated with the FILES attribute of request objects,
151         see :doc:`django:topics/http/file-uploads`
152 
153         :param request: Request submitted for saving imprint form
154         :type request: ~django.http.HttpRequest
155 
156         :param args: The supplied arguments
157         :type args: list
158 
159         :param kwargs: The supplied keyword arguments
160         :type kwargs: dict
161 
162         :return: Redirection to the populated imprint form
163         :rtype: ~django.http.HttpResponseRedirect
164         """
165 
166         region = Region.get_current_region(request)
167         language = get_object_or_404(region.languages, slug=kwargs.get("language_slug"))
168 
169         try:
170             imprint_instance = region.imprint
171         except ImprintPage.DoesNotExist:
172             imprint_instance = None
173 
174         imprint_translation_instance = ImprintPageTranslation.objects.filter(
175             page=imprint_instance,
176             language=language,
177         ).first()
178 
179         imprint_translation_form = ImprintTranslationForm(
180             request.POST,
181             instance=imprint_translation_instance,
182             region=region,
183             language=language,
184         )
185 
186         side_by_side_language_options = self.get_side_by_side_language_options(
187             region, language, imprint_instance
188         )
189 
190         # TODO: error handling
191         if not imprint_translation_form.is_valid():
192             messages.error(request, _("Errors have occurred."))
193             return render(
194                 request,
195                 self.template_name,
196                 {
197                     **self.base_context,
198                     "imprint_translation_form": imprint_translation_form,
199                     "imprint": imprint_instance,
200                     "language": language,
201                     # Languages for tab view
202                     "languages": region.languages if imprint_instance else [language],
203                     "side_by_side_language_options": side_by_side_language_options,
204                 },
205             )
206 
207         if not imprint_translation_form.has_changed():
208             messages.info(request, _("No changes detected."))
209             return render(
210                 request,
211                 self.template_name,
212                 {
213                     **self.base_context,
214                     "imprint_translation_form": imprint_translation_form,
215                     "imprint": imprint_instance,
216                     "language": language,
217                     # Languages for tab view
218                     "languages": region.languages if imprint_instance else [language],
219                     "side_by_side_language_options": side_by_side_language_options,
220                 },
221             )
222 
223         if not imprint_instance:
224             imprint = ImprintPage.objects.create(region=region)
225         imprint_translation = imprint_translation_form.save(
226             imprint=imprint,
227             user=request.user,
228         )
229 
230         published = imprint_translation.status == status.PUBLIC
231         if not imprint_instance:
232             if published:
233                 messages.success(
234                     request, _("imprint was successfully created and published")
235                 )
236             else:
237                 messages.success(request, _("imprint was successfully created"))
238         elif not imprint_translation_instance:
239             if published:
240                 messages.success(
241                     request, _("Translation was successfully created and published")
242                 )
243             else:
244                 messages.success(request, _("Translation was successfully created"))
245         else:
246             if published:
247                 messages.success(request, _("Translation was successfully published"))
248             else:
249                 messages.success(request, _("Translation was successfully saved"))
250 
251         return redirect(
252             "edit_imprint",
253             **{
254                 "region_slug": region.slug,
255                 "language_slug": language.slug,
256             },
257         )
258 
259     @staticmethod
260     def get_side_by_side_language_options(region, language, imprint):
261         """
262         This is a helper function to generate the side-by-side language options for both the get and post requests.
263 
264         :param region: The current region
265         :type region: ~cms.models.regions.region.Region
266 
267         :param language: The current language
268         :type language: ~cms.models.languages.language.Language
269 
270         :param imprint: The current imprint
271         :type imprint: ~cms.models.pages.imprint_page.ImprintPage
272 
273         :return: The list of language options, each represented by a dict
274         :rtype: list
275         """
276         side_by_side_language_options = []
277         for language_node in region.language_tree_nodes.all():
278             if language_node.parent:
279                 source_translation = ImprintPageTranslation.objects.filter(
280                     page=imprint,
281                     language=language_node.parent.language,
282                 )
283                 side_by_side_language_options.append(
284                     {
285                         "value": language_node.language.slug,
286                         "label": _("{source_language} to {target_language}").format(
287                             source_language=language_node.parent.language.translated_name,
288                             target_language=language_node.language.translated_name,
289                         ),
290                         "selected": language_node.language == language,
291                         "disabled": not source_translation.exists(),
292                     }
293                 )
294         return side_by_side_language_options
295
```
--- 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()

```

diff --git a/src/cms/views/imprint/imprint_view.py b/src/cms/views/imprint/imprint_view.py
--- a/src/cms/views/imprint/imprint_view.py
+++ b/src/cms/views/imprint/imprint_view.py
@@ -220,8 +220,8 @@
                 },
             )
 
-        if not imprint_instance:
-            imprint = ImprintPage.objects.create(region=region)
+        imprint = imprint_instance or ImprintPage.objects.create(region=region)
+
         imprint_translation = imprint_translation_form.save(
             imprint=imprint,
             user=request.user,

{"golden_diff": "diff --git a/src/cms/views/imprint/imprint_view.py b/src/cms/views/imprint/imprint_view.py\n--- a/src/cms/views/imprint/imprint_view.py\n+++ b/src/cms/views/imprint/imprint_view.py\n@@ -220,8 +220,8 @@\n                 },\n             )\n \n-        if not imprint_instance:\n-            imprint = ImprintPage.objects.create(region=region)\n+        imprint = imprint_instance or ImprintPage.objects.create(region=region)\n+\n         imprint_translation = imprint_translation_form.save(\n             imprint=imprint,\n             user=request.user,\n", "issue": "`UnboundLocalError` in imprint form\n### Describe the Bug\r\n<!-- A clear and concise description of what the bug is. -->\r\nThe imprint can only be created when it does not yet exist.\r\nOnce it exists, it cannot be changed anymore.\r\n\r\n### Steps to Reproduce\r\n\r\n1. Go to the imprint form\r\n2. Create imprint\r\n3. Change existing imprint translation\r\n4. See error\r\n\r\n### Expected Behavior\r\n<!-- A clear and concise description of what you expected to happen. -->\r\nThe imprint translation should be changed\r\n\r\n### Actual Behavior\r\n<!-- A clear and concise description of what actually happened. -->\r\n`UnboundLocalError at /augsburg/imprint/de/`\r\n`local variable 'imprint' referenced before assignment`\r\n### Additional Information\r\n<!-- Add any other context (e.g. logs, screenshots, etc.) about the problem here. -->\r\n\r\n<details>\r\n <summary>Traceback</summary>\r\n\r\n```\r\nEnvironment:\r\n\r\n\r\nRequest Method: POST\r\nRequest URL: http://localhost:8000/augsburg/imprint/de/\r\n\r\nDjango Version: 3.2.2\r\nPython Version: 3.7.10\r\nInstalled Applications:\r\n['cms.apps.CmsConfig',\r\n 'gvz_api.apps.GvzApiConfig',\r\n 'django.contrib.auth',\r\n 'django.contrib.contenttypes',\r\n 'django.contrib.messages',\r\n 'django.contrib.sessions',\r\n 'django.contrib.sitemaps',\r\n 'django.contrib.staticfiles',\r\n 'corsheaders',\r\n 'widget_tweaks',\r\n 'easy_thumbnails',\r\n 'filer',\r\n 'mptt',\r\n 'rules.apps.AutodiscoverRulesConfig',\r\n 'linkcheck',\r\n 'django.contrib.admin']\r\nInstalled Middleware:\r\n['corsheaders.middleware.CorsMiddleware',\r\n 'django.middleware.security.SecurityMiddleware',\r\n 'django.contrib.sessions.middleware.SessionMiddleware',\r\n 'django.middleware.locale.LocaleMiddleware',\r\n 'django.middleware.common.CommonMiddleware',\r\n 'django.middleware.csrf.CsrfViewMiddleware',\r\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\r\n 'django.contrib.messages.middleware.MessageMiddleware',\r\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\r\n 'cms.middleware.timezone_middleware.TimezoneMiddleware']\r\n\r\nTraceback (most recent call last):\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py\", line 47, in inner\r\n    response = get_response(request)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/core/handlers/base.py\", line 181, in _get_response\r\n    response = wrapped_callback(request, *callback_args, **callback_kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/views/generic/base.py\", line 70, in view\r\n    return self.dispatch(request, *args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/utils/decorators.py\", line 43, in _wrapper\r\n    return bound_method(*args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py\", line 21, in _wrapped_view\r\n    return view_func(request, *args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/utils/decorators.py\", line 43, in _wrapper\r\n    return bound_method(*args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/src/cms/decorators.py\", line 53, in wrap\r\n    return function(request, *args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/contrib/auth/mixins.py\", line 104, in dispatch\r\n    return super().dispatch(request, *args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/views/generic/base.py\", line 98, in dispatch\r\n    return handler(request, *args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/src/cms/views/imprint/imprint_view.py\", line 226, in post\r\n    imprint=imprint,\r\n\r\nException Type: UnboundLocalError at /augsburg/imprint/de/\r\nException Value: local variable 'imprint' referenced before assignment\r\n```\r\n\r\n</details>\n", "before_files": [{"content": "import logging\n\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.urls import reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.translation import ugettext as _\nfrom django.views.generic import TemplateView\n\nfrom backend.settings import IMPRINT_SLUG, WEBAPP_URL\nfrom ...constants import status\nfrom ...decorators import region_permission_required\nfrom ...forms import ImprintTranslationForm\nfrom ...models import ImprintPageTranslation, ImprintPage, Region\n\nlogger = logging.getLogger(__name__)\n\n\n@method_decorator(login_required, name=\"dispatch\")\n@method_decorator(region_permission_required, name=\"dispatch\")\nclass ImprintView(PermissionRequiredMixin, TemplateView):\n    \"\"\"\n    View for the imprint page form and imprint page translation form\n    \"\"\"\n\n    permission_required = \"cms.manage_imprint\"\n    raise_exception = True\n\n    template_name = \"imprint/imprint_form.html\"\n    base_context = {\n        \"current_menu_item\": \"imprint\",\n        \"WEBAPP_URL\": WEBAPP_URL,\n        \"IMPRINT_SLUG\": IMPRINT_SLUG,\n    }\n\n    def get(self, request, *args, **kwargs):\n        \"\"\"\n        Render :class:`~cms.forms.imprint.imprint_translation_form.ImprintTranslationForm`\n\n        :param request: The current request\n        :type request: ~django.http.HttpResponse\n\n        :param args: The supplied arguments\n        :type args: list\n\n        :param kwargs: The supplied keyword arguments\n        :type kwargs: dict\n\n        :raises ~django.core.exceptions.PermissionDenied: If user does not have the permission to edit the specific page\n\n        :return: The rendered template response\n        :rtype: ~django.template.response.TemplateResponse\n        \"\"\"\n\n        # current region\n        region = Region.get_current_region(request)\n\n        # current language\n        language_slug = kwargs.get(\"language_slug\")\n        if language_slug:\n            language = get_object_or_404(region.languages, slug=language_slug)\n        elif region.default_language:\n            return redirect(\n                \"edit_imprint\",\n                **{\n                    \"region_slug\": region.slug,\n                    \"language_slug\": region.default_language.slug,\n                },\n            )\n        else:\n            messages.error(\n                request,\n                _(\"Please create at least one language node before creating pages.\"),\n            )\n            return redirect(\n                \"language_tree\",\n                **{\n                    \"region_slug\": region.slug,\n                },\n            )\n\n        # get imprint and translation objects if they exist\n        try:\n            imprint = region.imprint\n        except ImprintPage.DoesNotExist:\n            imprint = None\n\n        imprint_translation = ImprintPageTranslation.objects.filter(\n            page=imprint,\n            language=language,\n        ).first()\n\n        # Make form disabled if user has no permission to manage the imprint\n        disabled = False\n        if imprint:\n            if imprint.archived:\n                disabled = True\n                messages.warning(\n                    request, _(\"You cannot manage the imprint because it is archived.\")\n                )\n            public_translation = imprint.get_public_translation(language.slug)\n            if public_translation and imprint_translation != public_translation:\n                messages.info(\n                    request,\n                    _(\n                        \"This is <b>not</b> the most recent public revision of this translation. Instead, <a href='%(revision_url)s' class='underline hover:no-underline'>revision %(revision)s</a> is shown in the apps.\"\n                    )\n                    % {\n                        \"revision_url\": reverse(\n                            \"imprint_revisions\",\n                            kwargs={\n                                \"region_slug\": region.slug,\n                                \"language_slug\": language.slug,\n                                \"selected_revision\": public_translation.version,\n                            },\n                        ),\n                        \"revision\": public_translation.version,\n                    },\n                )\n\n        imprint_translation_form = ImprintTranslationForm(\n            instance=imprint_translation, disabled=disabled\n        )\n\n        # Pass side by side language options\n        side_by_side_language_options = self.get_side_by_side_language_options(\n            region, language, imprint\n        )\n\n        return render(\n            request,\n            self.template_name,\n            {\n                **self.base_context,\n                \"imprint_translation_form\": imprint_translation_form,\n                \"imprint\": imprint,\n                \"language\": language,\n                # Languages for tab view\n                \"languages\": region.languages if imprint else [language],\n                \"side_by_side_language_options\": side_by_side_language_options,\n            },\n        )\n\n    # pylint: disable=too-many-branches,unused-argument\n    def post(self, request, *args, **kwargs):\n        \"\"\"\n        Binds the user input data to the imprint form and validates the input.\n        Forms containing images/files need to be additionally instantiated with the FILES attribute of request objects,\n        see :doc:`django:topics/http/file-uploads`\n\n        :param request: Request submitted for saving imprint form\n        :type request: ~django.http.HttpRequest\n\n        :param args: The supplied arguments\n        :type args: list\n\n        :param kwargs: The supplied keyword arguments\n        :type kwargs: dict\n\n        :return: Redirection to the populated imprint form\n        :rtype: ~django.http.HttpResponseRedirect\n        \"\"\"\n\n        region = Region.get_current_region(request)\n        language = get_object_or_404(region.languages, slug=kwargs.get(\"language_slug\"))\n\n        try:\n            imprint_instance = region.imprint\n        except ImprintPage.DoesNotExist:\n            imprint_instance = None\n\n        imprint_translation_instance = ImprintPageTranslation.objects.filter(\n            page=imprint_instance,\n            language=language,\n        ).first()\n\n        imprint_translation_form = ImprintTranslationForm(\n            request.POST,\n            instance=imprint_translation_instance,\n            region=region,\n            language=language,\n        )\n\n        side_by_side_language_options = self.get_side_by_side_language_options(\n            region, language, imprint_instance\n        )\n\n        # TODO: error handling\n        if not imprint_translation_form.is_valid():\n            messages.error(request, _(\"Errors have occurred.\"))\n            return render(\n                request,\n                self.template_name,\n                {\n                    **self.base_context,\n                    \"imprint_translation_form\": imprint_translation_form,\n                    \"imprint\": imprint_instance,\n                    \"language\": language,\n                    # Languages for tab view\n                    \"languages\": region.languages if imprint_instance else [language],\n                    \"side_by_side_language_options\": side_by_side_language_options,\n                },\n            )\n\n        if not imprint_translation_form.has_changed():\n            messages.info(request, _(\"No changes detected.\"))\n            return render(\n                request,\n                self.template_name,\n                {\n                    **self.base_context,\n                    \"imprint_translation_form\": imprint_translation_form,\n                    \"imprint\": imprint_instance,\n                    \"language\": language,\n                    # Languages for tab view\n                    \"languages\": region.languages if imprint_instance else [language],\n                    \"side_by_side_language_options\": side_by_side_language_options,\n                },\n            )\n\n        if not imprint_instance:\n            imprint = ImprintPage.objects.create(region=region)\n        imprint_translation = imprint_translation_form.save(\n            imprint=imprint,\n            user=request.user,\n        )\n\n        published = imprint_translation.status == status.PUBLIC\n        if not imprint_instance:\n            if published:\n                messages.success(\n                    request, _(\"imprint was successfully created and published\")\n                )\n            else:\n                messages.success(request, _(\"imprint was successfully created\"))\n        elif not imprint_translation_instance:\n            if published:\n                messages.success(\n                    request, _(\"Translation was successfully created and published\")\n                )\n            else:\n                messages.success(request, _(\"Translation was successfully created\"))\n        else:\n            if published:\n                messages.success(request, _(\"Translation was successfully published\"))\n            else:\n                messages.success(request, _(\"Translation was successfully saved\"))\n\n        return redirect(\n            \"edit_imprint\",\n            **{\n                \"region_slug\": region.slug,\n                \"language_slug\": language.slug,\n            },\n        )\n\n    @staticmethod\n    def get_side_by_side_language_options(region, language, imprint):\n        \"\"\"\n        This is a helper function to generate the side-by-side language options for both the get and post requests.\n\n        :param region: The current region\n        :type region: ~cms.models.regions.region.Region\n\n        :param language: The current language\n        :type language: ~cms.models.languages.language.Language\n\n        :param imprint: The current imprint\n        :type imprint: ~cms.models.pages.imprint_page.ImprintPage\n\n        :return: The list of language options, each represented by a dict\n        :rtype: list\n        \"\"\"\n        side_by_side_language_options = []\n        for language_node in region.language_tree_nodes.all():\n            if language_node.parent:\n                source_translation = ImprintPageTranslation.objects.filter(\n                    page=imprint,\n                    language=language_node.parent.language,\n                )\n                side_by_side_language_options.append(\n                    {\n                        \"value\": language_node.language.slug,\n                        \"label\": _(\"{source_language} to {target_language}\").format(\n                            source_language=language_node.parent.language.translated_name,\n                            target_language=language_node.language.translated_name,\n                        ),\n                        \"selected\": language_node.language == language,\n                        \"disabled\": not source_translation.exists(),\n                    }\n                )\n        return side_by_side_language_options\n", "path": "src/cms/views/imprint/imprint_view.py"}], "after_files": [{"content": "import logging\n\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.urls import reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.translation import ugettext as _\nfrom django.views.generic import TemplateView\n\nfrom backend.settings import IMPRINT_SLUG, WEBAPP_URL\nfrom ...constants import status\nfrom ...decorators import region_permission_required\nfrom ...forms import ImprintTranslationForm\nfrom ...models import ImprintPageTranslation, ImprintPage, Region\n\nlogger = logging.getLogger(__name__)\n\n\n@method_decorator(login_required, name=\"dispatch\")\n@method_decorator(region_permission_required, name=\"dispatch\")\nclass ImprintView(PermissionRequiredMixin, TemplateView):\n    \"\"\"\n    View for the imprint page form and imprint page translation form\n    \"\"\"\n\n    permission_required = \"cms.manage_imprint\"\n    raise_exception = True\n\n    template_name = \"imprint/imprint_form.html\"\n    base_context = {\n        \"current_menu_item\": \"imprint\",\n        \"WEBAPP_URL\": WEBAPP_URL,\n        \"IMPRINT_SLUG\": IMPRINT_SLUG,\n    }\n\n    def get(self, request, *args, **kwargs):\n        \"\"\"\n        Render :class:`~cms.forms.imprint.imprint_translation_form.ImprintTranslationForm`\n\n        :param request: The current request\n        :type request: ~django.http.HttpResponse\n\n        :param args: The supplied arguments\n        :type args: list\n\n        :param kwargs: The supplied keyword arguments\n        :type kwargs: dict\n\n        :raises ~django.core.exceptions.PermissionDenied: If user does not have the permission to edit the specific page\n\n        :return: The rendered template response\n        :rtype: ~django.template.response.TemplateResponse\n        \"\"\"\n\n        # current region\n        region = Region.get_current_region(request)\n\n        # current language\n        language_slug = kwargs.get(\"language_slug\")\n        if language_slug:\n            language = get_object_or_404(region.languages, slug=language_slug)\n        elif region.default_language:\n            return redirect(\n                \"edit_imprint\",\n                **{\n                    \"region_slug\": region.slug,\n                    \"language_slug\": region.default_language.slug,\n                },\n            )\n        else:\n            messages.error(\n                request,\n                _(\"Please create at least one language node before creating pages.\"),\n            )\n            return redirect(\n                \"language_tree\",\n                **{\n                    \"region_slug\": region.slug,\n                },\n            )\n\n        # get imprint and translation objects if they exist\n        try:\n            imprint = region.imprint\n        except ImprintPage.DoesNotExist:\n            imprint = None\n\n        imprint_translation = ImprintPageTranslation.objects.filter(\n            page=imprint,\n            language=language,\n        ).first()\n\n        # Make form disabled if user has no permission to manage the imprint\n        disabled = False\n        if imprint:\n            if imprint.archived:\n                disabled = True\n                messages.warning(\n                    request, _(\"You cannot manage the imprint because it is archived.\")\n                )\n            public_translation = imprint.get_public_translation(language.slug)\n            if public_translation and imprint_translation != public_translation:\n                messages.info(\n                    request,\n                    _(\n                        \"This is <b>not</b> the most recent public revision of this translation. Instead, <a href='%(revision_url)s' class='underline hover:no-underline'>revision %(revision)s</a> is shown in the apps.\"\n                    )\n                    % {\n                        \"revision_url\": reverse(\n                            \"imprint_revisions\",\n                            kwargs={\n                                \"region_slug\": region.slug,\n                                \"language_slug\": language.slug,\n                                \"selected_revision\": public_translation.version,\n                            },\n                        ),\n                        \"revision\": public_translation.version,\n                    },\n                )\n\n        imprint_translation_form = ImprintTranslationForm(\n            instance=imprint_translation, disabled=disabled\n        )\n\n        # Pass side by side language options\n        side_by_side_language_options = self.get_side_by_side_language_options(\n            region, language, imprint\n        )\n\n        return render(\n            request,\n            self.template_name,\n            {\n                **self.base_context,\n                \"imprint_translation_form\": imprint_translation_form,\n                \"imprint\": imprint,\n                \"language\": language,\n                # Languages for tab view\n                \"languages\": region.languages if imprint else [language],\n                \"side_by_side_language_options\": side_by_side_language_options,\n            },\n        )\n\n    # pylint: disable=too-many-branches,unused-argument\n    def post(self, request, *args, **kwargs):\n        \"\"\"\n        Binds the user input data to the imprint form and validates the input.\n        Forms containing images/files need to be additionally instantiated with the FILES attribute of request objects,\n        see :doc:`django:topics/http/file-uploads`\n\n        :param request: Request submitted for saving imprint form\n        :type request: ~django.http.HttpRequest\n\n        :param args: The supplied arguments\n        :type args: list\n\n        :param kwargs: The supplied keyword arguments\n        :type kwargs: dict\n\n        :return: Redirection to the populated imprint form\n        :rtype: ~django.http.HttpResponseRedirect\n        \"\"\"\n\n        region = Region.get_current_region(request)\n        language = get_object_or_404(region.languages, slug=kwargs.get(\"language_slug\"))\n\n        try:\n            imprint_instance = region.imprint\n        except ImprintPage.DoesNotExist:\n            imprint_instance = None\n\n        imprint_translation_instance = ImprintPageTranslation.objects.filter(\n            page=imprint_instance,\n            language=language,\n        ).first()\n\n        imprint_translation_form = ImprintTranslationForm(\n            request.POST,\n            instance=imprint_translation_instance,\n            region=region,\n            language=language,\n        )\n\n        side_by_side_language_options = self.get_side_by_side_language_options(\n            region, language, imprint_instance\n        )\n\n        # TODO: error handling\n        if not imprint_translation_form.is_valid():\n            messages.error(request, _(\"Errors have occurred.\"))\n            return render(\n                request,\n                self.template_name,\n                {\n                    **self.base_context,\n                    \"imprint_translation_form\": imprint_translation_form,\n                    \"imprint\": imprint_instance,\n                    \"language\": language,\n                    # Languages for tab view\n                    \"languages\": region.languages if imprint_instance else [language],\n                    \"side_by_side_language_options\": side_by_side_language_options,\n                },\n            )\n\n        if not imprint_translation_form.has_changed():\n            messages.info(request, _(\"No changes detected.\"))\n            return render(\n                request,\n                self.template_name,\n                {\n                    **self.base_context,\n                    \"imprint_translation_form\": imprint_translation_form,\n                    \"imprint\": imprint_instance,\n                    \"language\": language,\n                    # Languages for tab view\n                    \"languages\": region.languages if imprint_instance else [language],\n                    \"side_by_side_language_options\": side_by_side_language_options,\n                },\n            )\n\n        imprint = imprint_instance or ImprintPage.objects.create(region=region)\n\n        imprint_translation = imprint_translation_form.save(\n            imprint=imprint,\n            user=request.user,\n        )\n\n        published = imprint_translation.status == status.PUBLIC\n        if not imprint_instance:\n            if published:\n                messages.success(\n                    request, _(\"imprint was successfully created and published\")\n                )\n            else:\n                messages.success(request, _(\"imprint was successfully created\"))\n        elif not imprint_translation_instance:\n            if published:\n                messages.success(\n                    request, _(\"Translation was successfully created and published\")\n                )\n            else:\n                messages.success(request, _(\"Translation was successfully created\"))\n        else:\n            if published:\n                messages.success(request, _(\"Translation was successfully published\"))\n            else:\n                messages.success(request, _(\"Translation was successfully saved\"))\n\n        return redirect(\n            \"edit_imprint\",\n            **{\n                \"region_slug\": region.slug,\n                \"language_slug\": language.slug,\n            },\n        )\n\n    @staticmethod\n    def get_side_by_side_language_options(region, language, imprint):\n        \"\"\"\n        This is a helper function to generate the side-by-side language options for both the get and post requests.\n\n        :param region: The current region\n        :type region: ~cms.models.regions.region.Region\n\n        :param language: The current language\n        :type language: ~cms.models.languages.language.Language\n\n        :param imprint: The current imprint\n        :type imprint: ~cms.models.pages.imprint_page.ImprintPage\n\n        :return: The list of language options, each represented by a dict\n        :rtype: list\n        \"\"\"\n        side_by_side_language_options = []\n        for language_node in region.language_tree_nodes.all():\n            if language_node.parent:\n                source_translation = ImprintPageTranslation.objects.filter(\n                    page=imprint,\n                    language=language_node.parent.language,\n                )\n                side_by_side_language_options.append(\n                    {\n                        \"value\": language_node.language.slug,\n                        \"label\": _(\"{source_language} to {target_language}\").format(\n                            source_language=language_node.parent.language.translated_name,\n                            target_language=language_node.language.translated_name,\n                        ),\n                        \"selected\": language_node.language == language,\n                        \"disabled\": not source_translation.exists(),\n                    }\n                )\n        return side_by_side_language_options\n", "path": "src/cms/views/imprint/imprint_view.py"}]}