We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype
# Request type
<!-- Select the appropriate option -->
- [ ] Please close this issue, I accidentally submitted it without adding any details
- [ ] New documentation
- [x] Correction or update


# Details
I was trying to make it redirect to the main `Array` document, but I can't edit it. (404)
Seems like that if the upstream document (`/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype`) is removed, localized ones throw 404 in `$edit`.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `kuma/wiki/views/translate.py`
Content:
```
1 from urllib.parse import urlencode
2 
3 from csp.decorators import csp_update
4 from django.conf import settings
5 from django.core.exceptions import ObjectDoesNotExist
6 from django.http import Http404, JsonResponse
7 from django.shortcuts import get_object_or_404, redirect, render
8 from django.utils.safestring import mark_safe
9 from django.utils.translation import ugettext_lazy as _
10 from django.views.decorators.cache import never_cache
11 
12 import kuma.wiki.content
13 from kuma.attachments.forms import AttachmentRevisionForm
14 from kuma.core.decorators import block_user_agents, ensure_wiki_domain, login_required
15 from kuma.core.i18n import get_language_mapping
16 from kuma.core.urlresolvers import reverse
17 from kuma.core.utils import get_object_or_none, smart_int, urlparams
18 
19 from .utils import document_form_initial, split_slug
20 from ..decorators import check_readonly, prevent_indexing, process_document_path
21 from ..forms import DocumentForm, RevisionForm
22 from ..models import Document, Revision
23 
24 
25 @ensure_wiki_domain
26 @never_cache
27 @block_user_agents
28 @login_required
29 @process_document_path
30 def select_locale(request, document_slug, document_locale):
31     """
32     Select a locale to translate the document to.
33     """
34     doc = get_object_or_404(Document, locale=document_locale, slug=document_slug)
35     return render(request, "wiki/select_locale.html", {"document": doc})
36 
37 
38 @ensure_wiki_domain
39 @never_cache
40 @block_user_agents
41 @login_required
42 @csp_update(SCRIPT_SRC="'unsafe-eval'")  # Required until CKEditor 4.7
43 @process_document_path
44 @check_readonly
45 @prevent_indexing
46 def translate(request, document_slug, document_locale):
47     """
48     Create a new translation of a wiki document.
49 
50     * document_slug is for the default locale
51     * translation is to the request locale
52     """
53     # TODO: Refactor this view into two views? (new, edit)
54     # That might help reduce the headache-inducing branchiness.
55 
56     # The parent document to translate from
57     try:
58         # Use '.all_objects' because the parent might have been soft deleted.
59         # And if we don't respect that fact, it would become impossible to
60         # edit a the child of it.
61         parent_doc = Document.all_objects.get(
62             locale=settings.WIKI_DEFAULT_LANGUAGE, slug=document_slug
63         )
64     except Document.DoesNotExist:
65         raise Http404("Parent document does not exist")
66 
67     # Get the mapping here and now so it can be used for input validation
68     language_mapping = get_language_mapping()
69 
70     # HACK: Seems weird, but sticking the translate-to locale in a query
71     # param is the best way to avoid the MindTouch-legacy locale
72     # redirection logic.
73     document_locale = request.GET.get("tolocale", document_locale)
74     if document_locale.lower() not in language_mapping:
75         # The 'tolocale' query string parameters aren't free-text. They're
76         # explicitly listed on the "Select language" page (`...$locales`)
77         # If a locale was entered that wasn't a link it's a user bug.
78         raise Http404
79 
80     # Set a "Discard Changes" page
81     discard_href = ""
82 
83     if settings.WIKI_DEFAULT_LANGUAGE == document_locale:
84         # Don't translate to the default language.
85         return redirect(
86             reverse(
87                 "wiki.edit",
88                 locale=settings.WIKI_DEFAULT_LANGUAGE,
89                 args=[parent_doc.slug],
90             )
91         )
92 
93     if not parent_doc.is_localizable:
94         message = _("You cannot translate this document.")
95         context = {"message": message}
96         return render(request, "handlers/400.html", context, status=400)
97 
98     based_on_rev = parent_doc.current_or_latest_revision()
99 
100     disclose_description = bool(request.GET.get("opendescription"))
101 
102     try:
103         doc = parent_doc.translations.get(locale=document_locale)
104         slug_dict = split_slug(doc.slug)
105     except Document.DoesNotExist:
106         doc = None
107         disclose_description = True
108         slug_dict = split_slug(document_slug)
109 
110         # Find the "real" parent topic, which is its translation
111         if parent_doc.parent_topic:
112             try:
113                 parent_topic_translated_doc = parent_doc.parent_topic.translations.get(
114                     locale=document_locale
115                 )
116                 slug_dict = split_slug(
117                     parent_topic_translated_doc.slug + "/" + slug_dict["specific"]
118                 )
119             except ObjectDoesNotExist:
120                 pass
121 
122     user_has_doc_perm = (not doc) or (doc and doc.allows_editing_by(request.user))
123 
124     doc_form = None
125     if user_has_doc_perm:
126         if doc:
127             # If there's an existing doc, populate form from it.
128             discard_href = doc.get_absolute_url()
129             doc.slug = slug_dict["specific"]
130             doc_initial = document_form_initial(doc)
131         else:
132             # If no existing doc, bring over the original title and slug.
133             discard_href = parent_doc.get_absolute_url()
134             doc_initial = {"title": based_on_rev.title, "slug": slug_dict["specific"]}
135         doc_form = DocumentForm(initial=doc_initial, parent_slug=slug_dict["parent"])
136 
137     initial = {
138         "based_on": based_on_rev.id,
139         "current_rev": doc.current_or_latest_revision().id if doc else None,
140         "comment": "",
141         "toc_depth": based_on_rev.toc_depth,
142         "localization_tags": ["inprogress"],
143     }
144     content = None
145     if not doc:
146         content = based_on_rev.content
147     if content:
148         # TODO: There will be no need to "filterEditorSafety" when the code
149         #       that calls "clean_content" on Revision.save is deployed to
150         #       production, AND the current revisions of all docs have had
151         #       their content cleaned with "clean_content".
152         initial.update(
153             content=kuma.wiki.content.parse(content).filterEditorSafety().serialize()
154         )
155     instance = doc and doc.current_or_latest_revision()
156     rev_form = RevisionForm(
157         request=request,
158         instance=instance,
159         initial=initial,
160         parent_slug=slug_dict["parent"],
161     )
162 
163     if request.method == "POST":
164         which_form = request.POST.get("form-type", "both")
165         doc_form_invalid = False
166 
167         # Grab the posted slug value in case it's invalid
168         posted_slug = request.POST.get("slug", slug_dict["specific"])
169 
170         if user_has_doc_perm and which_form in ["doc", "both"]:
171             disclose_description = True
172             post_data = request.POST.copy()
173 
174             post_data.update({"locale": document_locale})
175 
176             doc_form = DocumentForm(
177                 post_data, instance=doc, parent_slug=slug_dict["parent"]
178             )
179             doc_form.instance.locale = document_locale
180             doc_form.instance.parent = parent_doc
181 
182             if which_form == "both":
183                 # Sending a new copy of post so the slug change above
184                 # doesn't cause problems during validation
185                 rev_form = RevisionForm(
186                     request=request, data=post_data, parent_slug=slug_dict["parent"]
187                 )
188 
189             # If we are submitting the whole form, we need to check that
190             # the Revision is valid before saving the Document.
191             if doc_form.is_valid() and (which_form == "doc" or rev_form.is_valid()):
192                 doc = doc_form.save(parent=parent_doc)
193 
194                 if which_form == "doc":
195                     url = urlparams(doc.get_edit_url(), opendescription=1)
196                     return redirect(url)
197             else:
198                 doc_form.data["slug"] = posted_slug
199                 doc_form_invalid = True
200 
201         if doc and which_form in ["rev", "both"]:
202             post_data = request.POST.copy()
203             if "slug" not in post_data:
204                 post_data["slug"] = posted_slug
205 
206             # update the post data with the toc_depth of original
207             post_data["toc_depth"] = based_on_rev.toc_depth
208 
209             # Pass in the locale for the akistmet "blog_lang".
210             post_data["locale"] = document_locale
211 
212             rev_form = RevisionForm(
213                 request=request, data=post_data, parent_slug=slug_dict["parent"]
214             )
215             rev_form.instance.document = doc  # for rev_form.clean()
216 
217             if rev_form.is_valid() and not doc_form_invalid:
218                 parent_id = request.POST.get("parent_id", "")
219 
220                 # Attempt to set a parent
221                 if parent_id:
222                     try:
223                         parent_doc = get_object_or_404(Document, id=parent_id)
224                         rev_form.instance.document.parent = parent_doc
225                         doc.parent = parent_doc
226                         rev_form.instance.based_on.document = doc.original
227                     except Document.DoesNotExist:
228                         pass
229 
230                 rev_form.save(doc)
231                 # If this is an Ajax POST, then return a JsonResponse
232                 if request.is_ajax():
233                     data = {
234                         "error": False,
235                         "new_revision_id": rev_form.instance.id,
236                     }
237 
238                     return JsonResponse(data)
239 
240                 # Construct the redirect URL, adding any needed parameters
241                 url = doc.get_absolute_url()
242                 params = {}
243                 # Parameter for the document saved, so that we can delete the cached draft on load
244                 params["rev_saved"] = request.POST.get("current_rev", "")
245                 url = "%s?%s" % (url, urlencode(params))
246                 return redirect(url)
247             else:
248                 # If this is an Ajax POST, then return a JsonResponse with error
249                 if request.is_ajax():
250                     if "current_rev" in rev_form._errors:
251                         # Make the error message safe so the '<' and '>' don't
252                         # get turned into '&lt;' and '&gt;', respectively
253                         rev_form.errors["current_rev"][0] = mark_safe(
254                             rev_form.errors["current_rev"][0]
255                         )
256                     errors = [rev_form.errors[key][0] for key in rev_form.errors.keys()]
257                     data = {
258                         "error": True,
259                         "error_message": errors,
260                         "new_revision_id": rev_form.instance.id,
261                     }
262                     return JsonResponse(data=data)
263 
264     if doc:
265         from_id = smart_int(request.GET.get("from"), None)
266         to_id = smart_int(request.GET.get("to"), None)
267 
268         revision_from = get_object_or_none(Revision, pk=from_id, document=doc.parent)
269         revision_to = get_object_or_none(Revision, pk=to_id, document=doc.parent)
270     else:
271         revision_from = revision_to = None
272 
273     parent_split = split_slug(parent_doc.slug)
274 
275     language = language_mapping[document_locale.lower()]
276     default_locale = language_mapping[settings.WIKI_DEFAULT_LANGUAGE.lower()]
277 
278     context = {
279         "parent": parent_doc,
280         "document": doc,
281         "document_form": doc_form,
282         "revision_form": rev_form,
283         "locale": document_locale,
284         "default_locale": default_locale,
285         "language": language,
286         "based_on": based_on_rev,
287         "disclose_description": disclose_description,
288         "discard_href": discard_href,
289         "attachment_form": AttachmentRevisionForm(),
290         "specific_slug": parent_split["specific"],
291         "parent_slug": parent_split["parent"],
292         "revision_from": revision_from,
293         "revision_to": revision_to,
294     }
295     return render(request, "wiki/translate.html", context)
296
```
--- 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/kuma/wiki/views/translate.py b/kuma/wiki/views/translate.py
--- a/kuma/wiki/views/translate.py
+++ b/kuma/wiki/views/translate.py
@@ -220,7 +220,10 @@
                 # Attempt to set a parent
                 if parent_id:
                     try:
-                        parent_doc = get_object_or_404(Document, id=parent_id)
+                        try:
+                            parent_doc = Document.all_objects.get(id=parent_id)
+                        except Document.DoesNotExist:
+                            raise Http404("Parent document does not exist")
                         rev_form.instance.document.parent = parent_doc
                         doc.parent = parent_doc
                         rev_form.instance.based_on.document = doc.original

{"golden_diff": "diff --git a/kuma/wiki/views/translate.py b/kuma/wiki/views/translate.py\n--- a/kuma/wiki/views/translate.py\n+++ b/kuma/wiki/views/translate.py\n@@ -220,7 +220,10 @@\n                 # Attempt to set a parent\n                 if parent_id:\n                     try:\n-                        parent_doc = get_object_or_404(Document, id=parent_id)\n+                        try:\n+                            parent_doc = Document.all_objects.get(id=parent_id)\n+                        except Document.DoesNotExist:\n+                            raise Http404(\"Parent document does not exist\")\n                         rev_form.instance.document.parent = parent_doc\n                         doc.parent = parent_doc\n                         rev_form.instance.based_on.document = doc.original\n", "issue": "/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype\n# Request type\r\n<!-- Select the appropriate option -->\r\n- [ ] Please close this issue, I accidentally submitted it without adding any details\r\n- [ ] New documentation\r\n- [x] Correction or update\r\n\r\n\r\n# Details\r\nI was trying to make it redirect to the main `Array` document, but I can't edit it. (404)\r\nSeems like that if the upstream document (`/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype`) is removed, localized ones throw 404 in `$edit`.\n", "before_files": [{"content": "from urllib.parse import urlencode\n\nfrom csp.decorators import csp_update\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import Http404, JsonResponse\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.decorators.cache import never_cache\n\nimport kuma.wiki.content\nfrom kuma.attachments.forms import AttachmentRevisionForm\nfrom kuma.core.decorators import block_user_agents, ensure_wiki_domain, login_required\nfrom kuma.core.i18n import get_language_mapping\nfrom kuma.core.urlresolvers import reverse\nfrom kuma.core.utils import get_object_or_none, smart_int, urlparams\n\nfrom .utils import document_form_initial, split_slug\nfrom ..decorators import check_readonly, prevent_indexing, process_document_path\nfrom ..forms import DocumentForm, RevisionForm\nfrom ..models import Document, Revision\n\n\n@ensure_wiki_domain\n@never_cache\n@block_user_agents\n@login_required\n@process_document_path\ndef select_locale(request, document_slug, document_locale):\n    \"\"\"\n    Select a locale to translate the document to.\n    \"\"\"\n    doc = get_object_or_404(Document, locale=document_locale, slug=document_slug)\n    return render(request, \"wiki/select_locale.html\", {\"document\": doc})\n\n\n@ensure_wiki_domain\n@never_cache\n@block_user_agents\n@login_required\n@csp_update(SCRIPT_SRC=\"'unsafe-eval'\")  # Required until CKEditor 4.7\n@process_document_path\n@check_readonly\n@prevent_indexing\ndef translate(request, document_slug, document_locale):\n    \"\"\"\n    Create a new translation of a wiki document.\n\n    * document_slug is for the default locale\n    * translation is to the request locale\n    \"\"\"\n    # TODO: Refactor this view into two views? (new, edit)\n    # That might help reduce the headache-inducing branchiness.\n\n    # The parent document to translate from\n    try:\n        # Use '.all_objects' because the parent might have been soft deleted.\n        # And if we don't respect that fact, it would become impossible to\n        # edit a the child of it.\n        parent_doc = Document.all_objects.get(\n            locale=settings.WIKI_DEFAULT_LANGUAGE, slug=document_slug\n        )\n    except Document.DoesNotExist:\n        raise Http404(\"Parent document does not exist\")\n\n    # Get the mapping here and now so it can be used for input validation\n    language_mapping = get_language_mapping()\n\n    # HACK: Seems weird, but sticking the translate-to locale in a query\n    # param is the best way to avoid the MindTouch-legacy locale\n    # redirection logic.\n    document_locale = request.GET.get(\"tolocale\", document_locale)\n    if document_locale.lower() not in language_mapping:\n        # The 'tolocale' query string parameters aren't free-text. They're\n        # explicitly listed on the \"Select language\" page (`...$locales`)\n        # If a locale was entered that wasn't a link it's a user bug.\n        raise Http404\n\n    # Set a \"Discard Changes\" page\n    discard_href = \"\"\n\n    if settings.WIKI_DEFAULT_LANGUAGE == document_locale:\n        # Don't translate to the default language.\n        return redirect(\n            reverse(\n                \"wiki.edit\",\n                locale=settings.WIKI_DEFAULT_LANGUAGE,\n                args=[parent_doc.slug],\n            )\n        )\n\n    if not parent_doc.is_localizable:\n        message = _(\"You cannot translate this document.\")\n        context = {\"message\": message}\n        return render(request, \"handlers/400.html\", context, status=400)\n\n    based_on_rev = parent_doc.current_or_latest_revision()\n\n    disclose_description = bool(request.GET.get(\"opendescription\"))\n\n    try:\n        doc = parent_doc.translations.get(locale=document_locale)\n        slug_dict = split_slug(doc.slug)\n    except Document.DoesNotExist:\n        doc = None\n        disclose_description = True\n        slug_dict = split_slug(document_slug)\n\n        # Find the \"real\" parent topic, which is its translation\n        if parent_doc.parent_topic:\n            try:\n                parent_topic_translated_doc = parent_doc.parent_topic.translations.get(\n                    locale=document_locale\n                )\n                slug_dict = split_slug(\n                    parent_topic_translated_doc.slug + \"/\" + slug_dict[\"specific\"]\n                )\n            except ObjectDoesNotExist:\n                pass\n\n    user_has_doc_perm = (not doc) or (doc and doc.allows_editing_by(request.user))\n\n    doc_form = None\n    if user_has_doc_perm:\n        if doc:\n            # If there's an existing doc, populate form from it.\n            discard_href = doc.get_absolute_url()\n            doc.slug = slug_dict[\"specific\"]\n            doc_initial = document_form_initial(doc)\n        else:\n            # If no existing doc, bring over the original title and slug.\n            discard_href = parent_doc.get_absolute_url()\n            doc_initial = {\"title\": based_on_rev.title, \"slug\": slug_dict[\"specific\"]}\n        doc_form = DocumentForm(initial=doc_initial, parent_slug=slug_dict[\"parent\"])\n\n    initial = {\n        \"based_on\": based_on_rev.id,\n        \"current_rev\": doc.current_or_latest_revision().id if doc else None,\n        \"comment\": \"\",\n        \"toc_depth\": based_on_rev.toc_depth,\n        \"localization_tags\": [\"inprogress\"],\n    }\n    content = None\n    if not doc:\n        content = based_on_rev.content\n    if content:\n        # TODO: There will be no need to \"filterEditorSafety\" when the code\n        #       that calls \"clean_content\" on Revision.save is deployed to\n        #       production, AND the current revisions of all docs have had\n        #       their content cleaned with \"clean_content\".\n        initial.update(\n            content=kuma.wiki.content.parse(content).filterEditorSafety().serialize()\n        )\n    instance = doc and doc.current_or_latest_revision()\n    rev_form = RevisionForm(\n        request=request,\n        instance=instance,\n        initial=initial,\n        parent_slug=slug_dict[\"parent\"],\n    )\n\n    if request.method == \"POST\":\n        which_form = request.POST.get(\"form-type\", \"both\")\n        doc_form_invalid = False\n\n        # Grab the posted slug value in case it's invalid\n        posted_slug = request.POST.get(\"slug\", slug_dict[\"specific\"])\n\n        if user_has_doc_perm and which_form in [\"doc\", \"both\"]:\n            disclose_description = True\n            post_data = request.POST.copy()\n\n            post_data.update({\"locale\": document_locale})\n\n            doc_form = DocumentForm(\n                post_data, instance=doc, parent_slug=slug_dict[\"parent\"]\n            )\n            doc_form.instance.locale = document_locale\n            doc_form.instance.parent = parent_doc\n\n            if which_form == \"both\":\n                # Sending a new copy of post so the slug change above\n                # doesn't cause problems during validation\n                rev_form = RevisionForm(\n                    request=request, data=post_data, parent_slug=slug_dict[\"parent\"]\n                )\n\n            # If we are submitting the whole form, we need to check that\n            # the Revision is valid before saving the Document.\n            if doc_form.is_valid() and (which_form == \"doc\" or rev_form.is_valid()):\n                doc = doc_form.save(parent=parent_doc)\n\n                if which_form == \"doc\":\n                    url = urlparams(doc.get_edit_url(), opendescription=1)\n                    return redirect(url)\n            else:\n                doc_form.data[\"slug\"] = posted_slug\n                doc_form_invalid = True\n\n        if doc and which_form in [\"rev\", \"both\"]:\n            post_data = request.POST.copy()\n            if \"slug\" not in post_data:\n                post_data[\"slug\"] = posted_slug\n\n            # update the post data with the toc_depth of original\n            post_data[\"toc_depth\"] = based_on_rev.toc_depth\n\n            # Pass in the locale for the akistmet \"blog_lang\".\n            post_data[\"locale\"] = document_locale\n\n            rev_form = RevisionForm(\n                request=request, data=post_data, parent_slug=slug_dict[\"parent\"]\n            )\n            rev_form.instance.document = doc  # for rev_form.clean()\n\n            if rev_form.is_valid() and not doc_form_invalid:\n                parent_id = request.POST.get(\"parent_id\", \"\")\n\n                # Attempt to set a parent\n                if parent_id:\n                    try:\n                        parent_doc = get_object_or_404(Document, id=parent_id)\n                        rev_form.instance.document.parent = parent_doc\n                        doc.parent = parent_doc\n                        rev_form.instance.based_on.document = doc.original\n                    except Document.DoesNotExist:\n                        pass\n\n                rev_form.save(doc)\n                # If this is an Ajax POST, then return a JsonResponse\n                if request.is_ajax():\n                    data = {\n                        \"error\": False,\n                        \"new_revision_id\": rev_form.instance.id,\n                    }\n\n                    return JsonResponse(data)\n\n                # Construct the redirect URL, adding any needed parameters\n                url = doc.get_absolute_url()\n                params = {}\n                # Parameter for the document saved, so that we can delete the cached draft on load\n                params[\"rev_saved\"] = request.POST.get(\"current_rev\", \"\")\n                url = \"%s?%s\" % (url, urlencode(params))\n                return redirect(url)\n            else:\n                # If this is an Ajax POST, then return a JsonResponse with error\n                if request.is_ajax():\n                    if \"current_rev\" in rev_form._errors:\n                        # Make the error message safe so the '<' and '>' don't\n                        # get turned into '&lt;' and '&gt;', respectively\n                        rev_form.errors[\"current_rev\"][0] = mark_safe(\n                            rev_form.errors[\"current_rev\"][0]\n                        )\n                    errors = [rev_form.errors[key][0] for key in rev_form.errors.keys()]\n                    data = {\n                        \"error\": True,\n                        \"error_message\": errors,\n                        \"new_revision_id\": rev_form.instance.id,\n                    }\n                    return JsonResponse(data=data)\n\n    if doc:\n        from_id = smart_int(request.GET.get(\"from\"), None)\n        to_id = smart_int(request.GET.get(\"to\"), None)\n\n        revision_from = get_object_or_none(Revision, pk=from_id, document=doc.parent)\n        revision_to = get_object_or_none(Revision, pk=to_id, document=doc.parent)\n    else:\n        revision_from = revision_to = None\n\n    parent_split = split_slug(parent_doc.slug)\n\n    language = language_mapping[document_locale.lower()]\n    default_locale = language_mapping[settings.WIKI_DEFAULT_LANGUAGE.lower()]\n\n    context = {\n        \"parent\": parent_doc,\n        \"document\": doc,\n        \"document_form\": doc_form,\n        \"revision_form\": rev_form,\n        \"locale\": document_locale,\n        \"default_locale\": default_locale,\n        \"language\": language,\n        \"based_on\": based_on_rev,\n        \"disclose_description\": disclose_description,\n        \"discard_href\": discard_href,\n        \"attachment_form\": AttachmentRevisionForm(),\n        \"specific_slug\": parent_split[\"specific\"],\n        \"parent_slug\": parent_split[\"parent\"],\n        \"revision_from\": revision_from,\n        \"revision_to\": revision_to,\n    }\n    return render(request, \"wiki/translate.html\", context)\n", "path": "kuma/wiki/views/translate.py"}], "after_files": [{"content": "from urllib.parse import urlencode\n\nfrom csp.decorators import csp_update\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import Http404, JsonResponse\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.decorators.cache import never_cache\n\nimport kuma.wiki.content\nfrom kuma.attachments.forms import AttachmentRevisionForm\nfrom kuma.core.decorators import block_user_agents, ensure_wiki_domain, login_required\nfrom kuma.core.i18n import get_language_mapping\nfrom kuma.core.urlresolvers import reverse\nfrom kuma.core.utils import get_object_or_none, smart_int, urlparams\n\nfrom .utils import document_form_initial, split_slug\nfrom ..decorators import check_readonly, prevent_indexing, process_document_path\nfrom ..forms import DocumentForm, RevisionForm\nfrom ..models import Document, Revision\n\n\n@ensure_wiki_domain\n@never_cache\n@block_user_agents\n@login_required\n@process_document_path\ndef select_locale(request, document_slug, document_locale):\n    \"\"\"\n    Select a locale to translate the document to.\n    \"\"\"\n    doc = get_object_or_404(Document, locale=document_locale, slug=document_slug)\n    return render(request, \"wiki/select_locale.html\", {\"document\": doc})\n\n\n@ensure_wiki_domain\n@never_cache\n@block_user_agents\n@login_required\n@csp_update(SCRIPT_SRC=\"'unsafe-eval'\")  # Required until CKEditor 4.7\n@process_document_path\n@check_readonly\n@prevent_indexing\ndef translate(request, document_slug, document_locale):\n    \"\"\"\n    Create a new translation of a wiki document.\n\n    * document_slug is for the default locale\n    * translation is to the request locale\n    \"\"\"\n    # TODO: Refactor this view into two views? (new, edit)\n    # That might help reduce the headache-inducing branchiness.\n\n    # The parent document to translate from\n    try:\n        # Use '.all_objects' because the parent might have been soft deleted.\n        # And if we don't respect that fact, it would become impossible to\n        # edit a the child of it.\n        parent_doc = Document.all_objects.get(\n            locale=settings.WIKI_DEFAULT_LANGUAGE, slug=document_slug\n        )\n    except Document.DoesNotExist:\n        raise Http404(\"Parent document does not exist\")\n\n    # Get the mapping here and now so it can be used for input validation\n    language_mapping = get_language_mapping()\n\n    # HACK: Seems weird, but sticking the translate-to locale in a query\n    # param is the best way to avoid the MindTouch-legacy locale\n    # redirection logic.\n    document_locale = request.GET.get(\"tolocale\", document_locale)\n    if document_locale.lower() not in language_mapping:\n        # The 'tolocale' query string parameters aren't free-text. They're\n        # explicitly listed on the \"Select language\" page (`...$locales`)\n        # If a locale was entered that wasn't a link it's a user bug.\n        raise Http404\n\n    # Set a \"Discard Changes\" page\n    discard_href = \"\"\n\n    if settings.WIKI_DEFAULT_LANGUAGE == document_locale:\n        # Don't translate to the default language.\n        return redirect(\n            reverse(\n                \"wiki.edit\",\n                locale=settings.WIKI_DEFAULT_LANGUAGE,\n                args=[parent_doc.slug],\n            )\n        )\n\n    if not parent_doc.is_localizable:\n        message = _(\"You cannot translate this document.\")\n        context = {\"message\": message}\n        return render(request, \"handlers/400.html\", context, status=400)\n\n    based_on_rev = parent_doc.current_or_latest_revision()\n\n    disclose_description = bool(request.GET.get(\"opendescription\"))\n\n    try:\n        doc = parent_doc.translations.get(locale=document_locale)\n        slug_dict = split_slug(doc.slug)\n    except Document.DoesNotExist:\n        doc = None\n        disclose_description = True\n        slug_dict = split_slug(document_slug)\n\n        # Find the \"real\" parent topic, which is its translation\n        if parent_doc.parent_topic:\n            try:\n                parent_topic_translated_doc = parent_doc.parent_topic.translations.get(\n                    locale=document_locale\n                )\n                slug_dict = split_slug(\n                    parent_topic_translated_doc.slug + \"/\" + slug_dict[\"specific\"]\n                )\n            except ObjectDoesNotExist:\n                pass\n\n    user_has_doc_perm = (not doc) or (doc and doc.allows_editing_by(request.user))\n\n    doc_form = None\n    if user_has_doc_perm:\n        if doc:\n            # If there's an existing doc, populate form from it.\n            discard_href = doc.get_absolute_url()\n            doc.slug = slug_dict[\"specific\"]\n            doc_initial = document_form_initial(doc)\n        else:\n            # If no existing doc, bring over the original title and slug.\n            discard_href = parent_doc.get_absolute_url()\n            doc_initial = {\"title\": based_on_rev.title, \"slug\": slug_dict[\"specific\"]}\n        doc_form = DocumentForm(initial=doc_initial, parent_slug=slug_dict[\"parent\"])\n\n    initial = {\n        \"based_on\": based_on_rev.id,\n        \"current_rev\": doc.current_or_latest_revision().id if doc else None,\n        \"comment\": \"\",\n        \"toc_depth\": based_on_rev.toc_depth,\n        \"localization_tags\": [\"inprogress\"],\n    }\n    content = None\n    if not doc:\n        content = based_on_rev.content\n    if content:\n        # TODO: There will be no need to \"filterEditorSafety\" when the code\n        #       that calls \"clean_content\" on Revision.save is deployed to\n        #       production, AND the current revisions of all docs have had\n        #       their content cleaned with \"clean_content\".\n        initial.update(\n            content=kuma.wiki.content.parse(content).filterEditorSafety().serialize()\n        )\n    instance = doc and doc.current_or_latest_revision()\n    rev_form = RevisionForm(\n        request=request,\n        instance=instance,\n        initial=initial,\n        parent_slug=slug_dict[\"parent\"],\n    )\n\n    if request.method == \"POST\":\n        which_form = request.POST.get(\"form-type\", \"both\")\n        doc_form_invalid = False\n\n        # Grab the posted slug value in case it's invalid\n        posted_slug = request.POST.get(\"slug\", slug_dict[\"specific\"])\n\n        if user_has_doc_perm and which_form in [\"doc\", \"both\"]:\n            disclose_description = True\n            post_data = request.POST.copy()\n\n            post_data.update({\"locale\": document_locale})\n\n            doc_form = DocumentForm(\n                post_data, instance=doc, parent_slug=slug_dict[\"parent\"]\n            )\n            doc_form.instance.locale = document_locale\n            doc_form.instance.parent = parent_doc\n\n            if which_form == \"both\":\n                # Sending a new copy of post so the slug change above\n                # doesn't cause problems during validation\n                rev_form = RevisionForm(\n                    request=request, data=post_data, parent_slug=slug_dict[\"parent\"]\n                )\n\n            # If we are submitting the whole form, we need to check that\n            # the Revision is valid before saving the Document.\n            if doc_form.is_valid() and (which_form == \"doc\" or rev_form.is_valid()):\n                doc = doc_form.save(parent=parent_doc)\n\n                if which_form == \"doc\":\n                    url = urlparams(doc.get_edit_url(), opendescription=1)\n                    return redirect(url)\n            else:\n                doc_form.data[\"slug\"] = posted_slug\n                doc_form_invalid = True\n\n        if doc and which_form in [\"rev\", \"both\"]:\n            post_data = request.POST.copy()\n            if \"slug\" not in post_data:\n                post_data[\"slug\"] = posted_slug\n\n            # update the post data with the toc_depth of original\n            post_data[\"toc_depth\"] = based_on_rev.toc_depth\n\n            # Pass in the locale for the akistmet \"blog_lang\".\n            post_data[\"locale\"] = document_locale\n\n            rev_form = RevisionForm(\n                request=request, data=post_data, parent_slug=slug_dict[\"parent\"]\n            )\n            rev_form.instance.document = doc  # for rev_form.clean()\n\n            if rev_form.is_valid() and not doc_form_invalid:\n                parent_id = request.POST.get(\"parent_id\", \"\")\n\n                # Attempt to set a parent\n                if parent_id:\n                    try:\n                        try:\n                            parent_doc = Document.all_objects.get(id=parent_id)\n                        except Document.DoesNotExist:\n                            raise Http404(\"Parent document does not exist\")\n                        rev_form.instance.document.parent = parent_doc\n                        doc.parent = parent_doc\n                        rev_form.instance.based_on.document = doc.original\n                    except Document.DoesNotExist:\n                        pass\n\n                rev_form.save(doc)\n                # If this is an Ajax POST, then return a JsonResponse\n                if request.is_ajax():\n                    data = {\n                        \"error\": False,\n                        \"new_revision_id\": rev_form.instance.id,\n                    }\n\n                    return JsonResponse(data)\n\n                # Construct the redirect URL, adding any needed parameters\n                url = doc.get_absolute_url()\n                params = {}\n                # Parameter for the document saved, so that we can delete the cached draft on load\n                params[\"rev_saved\"] = request.POST.get(\"current_rev\", \"\")\n                url = \"%s?%s\" % (url, urlencode(params))\n                return redirect(url)\n            else:\n                # If this is an Ajax POST, then return a JsonResponse with error\n                if request.is_ajax():\n                    if \"current_rev\" in rev_form._errors:\n                        # Make the error message safe so the '<' and '>' don't\n                        # get turned into '&lt;' and '&gt;', respectively\n                        rev_form.errors[\"current_rev\"][0] = mark_safe(\n                            rev_form.errors[\"current_rev\"][0]\n                        )\n                    errors = [rev_form.errors[key][0] for key in rev_form.errors.keys()]\n                    data = {\n                        \"error\": True,\n                        \"error_message\": errors,\n                        \"new_revision_id\": rev_form.instance.id,\n                    }\n                    return JsonResponse(data=data)\n\n    if doc:\n        from_id = smart_int(request.GET.get(\"from\"), None)\n        to_id = smart_int(request.GET.get(\"to\"), None)\n\n        revision_from = get_object_or_none(Revision, pk=from_id, document=doc.parent)\n        revision_to = get_object_or_none(Revision, pk=to_id, document=doc.parent)\n    else:\n        revision_from = revision_to = None\n\n    parent_split = split_slug(parent_doc.slug)\n\n    language = language_mapping[document_locale.lower()]\n    default_locale = language_mapping[settings.WIKI_DEFAULT_LANGUAGE.lower()]\n\n    context = {\n        \"parent\": parent_doc,\n        \"document\": doc,\n        \"document_form\": doc_form,\n        \"revision_form\": rev_form,\n        \"locale\": document_locale,\n        \"default_locale\": default_locale,\n        \"language\": language,\n        \"based_on\": based_on_rev,\n        \"disclose_description\": disclose_description,\n        \"discard_href\": discard_href,\n        \"attachment_form\": AttachmentRevisionForm(),\n        \"specific_slug\": parent_split[\"specific\"],\n        \"parent_slug\": parent_split[\"parent\"],\n        \"revision_from\": revision_from,\n        \"revision_to\": revision_to,\n    }\n    return render(request, \"wiki/translate.html\", context)\n", "path": "kuma/wiki/views/translate.py"}]}