<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abdelilah Khossan on Medium]]></title>
        <description><![CDATA[Stories by Abdelilah Khossan on Medium]]></description>
        <link>https://medium.com/@abdelilah.khossan?source=rss-77f204edcfb9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Abdelilah Khossan on Medium</title>
            <link>https://medium.com/@abdelilah.khossan?source=rss-77f204edcfb9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:48:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdelilah.khossan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Django internationalization debunked [Part 2]]]></title>
            <link>https://medium.com/@abdelilah.khossan/django-internationalization-debunked-part-2-3bf864c5d60e?source=rss-77f204edcfb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bf864c5d60e</guid>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[internationalization]]></category>
            <dc:creator><![CDATA[Abdelilah Khossan]]></dc:creator>
            <pubDate>Sun, 20 Nov 2022 22:50:33 GMT</pubDate>
            <atom:updated>2022-11-20T22:57:00.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rt8bysQIo5fHJkNe" /></figure><p>In Part1 we covered the basic things that are required to set up i18n with Django, we saw how to translate strings in Python code, how to mark strings as translatable in HTML templates. We discovered the functions and template tags that Django offers to accomplish the “targetting” task.</p><p>In this part we are going to discover how we can make javascript code translatable. Here we mean code that is written in seperate independant Javascript files (.js), not the code that is written inside HTML templates (between &lt;script&gt; tags), the latter can be dealt with the same way we deal with regular HTML strings. as always examples are more expressive than words, so let’s get started with concrete stuff.</p><h4>Configuration and targetting</h4><p>First we need to install <a href="https://django-statici18n.readthedocs.io/en/v2.3.1/"><em>django-statici18n</em></a> package</p><pre>pip install django-statici18n</pre><p>Next thing is to add it to list of installed apps:</p><pre>INSTALLED_APPS = [<br>    # ...<br>    &#39;statici18n&#39;,<br>    # ...<br>]</pre><p>Now we target strings target of translation in Javascript source code, as discussed above, we have two scenarios, Js code that is inside HTML templates, and the one inside .js files, the first one will be handled almost like normal HTML code, let see the following example:</p><pre>{% load i18n %}<br>&lt;body&gt;<br>...<br>&lt;script&gt;<br>$(document).ready(function () {<br>  // We use<br>  $(&#39;.dropify&#39;).dropify({<br>      messages: {<br>          replace: &#39;{% translate &quot;Sleep een bestand hiernaar toe of klik hier om te vervangen...&quot; %}&#39;,<br>          remove: &#39;{% translate &quot;Verwijderen&quot; %}&#39;,<br>          error: &#39;{% translate &quot;Spijtig, dit bestand is te groot&quot; %}&#39;,<br>      }<br>  });<br>};<br>&lt;/script&gt;<br>....<br>&lt;/body&gt;</pre><p>We can clearly see in the example above that we use <em>{% translate %}</em> template tag the same way we use it for simple HTML text nodes, so nothing is so special about Javascript code that is inside HTML templates.</p><p>Unlike HTML templates, independant Javascript files are handled differently. We target strings using a global function offered by <em>statici18n</em>, this function is <strong>gettext()</strong>. in order to use it, it is necessary to include the script where it is defined.</p><p>first of all, we need to load the statici18n in the template from which we reference the javascript file</p><pre>{% load statici18n %}<br><br>  &lt;!-- Your HTML markup goes here --&gt;<br>...<br>&lt;!-- Load statici18n script (contains the definition of gettext --&gt;<br>&lt;script src=&quot;{% statici18n LANGUAGE_CODE %}&quot;&gt;&lt;/script&gt;<br><br>&lt;!-- Then load all your scripts that contains translatable strings --&gt;<br>&lt;script src=&quot;script_with_translatable_strings.js&quot;&gt; &lt;/script&gt;</pre><p>also add &lt;script src=&quot;{% statici18n LANGUAGE_CODE %}&quot;&gt;&lt;/script&gt; before all the script tags referencing your translatable Javascript files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/0*8vBXeSHbdpsNneVW" /></figure><p>Now you can feel joy targetting your strings in Javascript code 👨‍💻 , with the magic of <strong>gettext</strong> function.</p><pre>swal.fire({<br>    title: gettext(&quot;Javascript is fun&quot;),<br>    icon: &quot;info&quot;,<br>    showCancelButton: true,<br>    confirmButtonText: gettext(&quot;Confirm&quot;),<br>    cancelButtonText: gettext(&quot;Cancel&quot;),<br>    showLoaderOnConfirm: true,<br>});</pre><p>Sometimes you may have strings with variables inside. interpolated strings are also supported for translation. <em>statici18n</em> puts at our disposal another function 😃 ; <strong>interpolate</strong> is used alongside with <strong>gettext</strong> to get the job done ✅</p><p>The <strong>interpolate</strong> function supports dynamically populating a format string. The interpolation syntax is borrowed from Python, so the <strong>interpolate</strong> function supports both positional and named interpolation:</p><p>Again let’s illustrate this in the following example:</p><pre>// Positional interpolation<br>// values are sequentially interpolated in the order of format placeholders<br>let format = gettext(&quot;Let&#39;s count from %s to %s&quot;);<br>result = interpolate(format, [42, 1337]);<br><br>// Named interpolation<br>// This mode is selected by passing the optional boolean <br>// named parameter as true<br>format = gettext(&quot;This is Part %(part_number)s of i18n article series&quot;)<br><br>result = interpolate(format, {part_number: 2}, true),</pre><h4><strong>Generating translations</strong></h4><p>The command makemessages we have seen in Part I extracts strings also from Javascript files, and are collected in djangojs.po portable object files. The translator’s job to fill in the corresponding translations.</p><p>Time to borrow some magic tricks from Django CLI. as with Python and HTML code, we do have similar command like compilemessages for Javascript code; the command is <strong>compilejsi18n</strong> offered by <em>django-statici18n</em> package. We run this command to get <strong>djangojs.js</strong>files under /<em>static</em> folder in the hierarchy shown in the picture below;</p><pre>python manage.py compilejsi18n</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*X7C4jRyYW2ns-i9p2UgwwA.png" /></figure><p><strong>djangojs.js </strong>files are generated for each available language, they contain filled translations from .po files. made available in form of a global Javascript object. In case you are curious here is what it looks like:</p><pre><br>// Defintion of gettext library<br>// ...<br><br>// Definition of the catalogue containing translations<br><br>  django.catalog = django.catalog || {};<br>  <br>  const newcatalog = {<br>    &quot;Dog&quot;: &quot;chien&quot;,<br>    &quot;Cow&quot;: &quot;Vache&quot;,<br>    &quot;Cat&quot;: &quot;Chat&quot;,<br>    // ...<br>  }<br><br>// ...</pre><p>Until now we covered the basic stuff enough to put you on the right track, believe it or not, now you are able to translate your Javascript files 😃</p><p>I hope you enjoyed this part II, the upcoming part will be dedicated to show some issues that you might encounter, and an innovative way to automate the translation process.</p><p>Stay tuned for the next part 😉.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bf864c5d60e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django internationalization debunked]]></title>
            <link>https://medium.com/@abdelilah.khossan/django-internationalization-debunked-fa368d21a133?source=rss-77f204edcfb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa368d21a133</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[i18n]]></category>
            <category><![CDATA[internationalization]]></category>
            <dc:creator><![CDATA[Abdelilah Khossan]]></dc:creator>
            <pubDate>Sun, 13 Nov 2022 12:08:29 GMT</pubDate>
            <atom:updated>2022-11-21T14:56:25.525Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong><em>Django internationalization debunked [Part 1]</em></strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*imnGcBm8bi8fOGpV" /><figcaption>Photo by <a href="https://unsplash.com/es/@faisaldada?utm_source=medium&amp;utm_medium=referral">Faisal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>The goal of <strong>internationalization</strong> and localization is to allow a single web application to offer its content in languages and formats tailored to the audience.</blockquote><p><strong><em>i18n</em></strong> module is definitely one of the most powerful tools that Django offers to developers. it enables web applications to become language aware, this means that the content of your web application is going to adapt to the end user’s language.</p><p>Django made the process of <em>internationalizing</em> web content very straightforward, with the help of i18n feature we are able to accomplish this on the fly. In this guide we are going to cover the very basic steps to do in order to get things going with internationalization, I assume the reader has basic knowledge of Django framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*4j6X7Bny28GaBDoh.png" /></figure><p>We suppose (again 😅 ) we have an existing Django project setup, with an app named <em>poll .</em></p><h4>Configuration 🛠</h4><p>To get things going with Django i18n module we need to add a bit of configuration to base_settings.py file</p><ul><li><strong>Enable i18n feature ✔️</strong></li></ul><pre>USE_I18N = True</pre><ul><li><strong>Add locale middleware to MIDDLEWARE list</strong></li></ul><p>It<strong> </strong>should<strong> </strong>come between Session and Common middlewares.</p><pre>MIDDLEWARE = [<br>    …<br>    &#39;django.middleware.locale.LocaleMiddleware&#39;, <br>    …<br>]</pre><ul><li><strong>Add i18n templates context processor</strong></li></ul><pre>TEMPLATES = [<br>    {<br>        &quot;OPTIONS&quot;: {<br>            &quot;context_processors&quot;: [<br>                ...,<br>                ## context processor for i18n<br>                &quot;django.template.context_processors.i18n&quot;,<br>                ...<br>            ],      <br>        },<br>    },<br>]</pre><ul><li><strong>Configure local paths</strong></li></ul><pre>LOCALE_PATHS = (os.path.join(BASE_DIR, &quot;locale&quot;),)</pre><ul><li><strong>Add a default language (fallback language) 🇺🇸</strong></li></ul><pre>LANGUAGE_CODE = &#39;en&#39;</pre><p><em>LANGUAGE_CODE</em> defines which language should be used by default. If is not specified, then project’s settings.LANGUAGE_CODE is used</p><ul><li><strong>Add a list of supported languages</strong></li></ul><pre>LANGUAGES = [<br>    (&#39;nl&#39;, gettext_noop(&#39;Nederlands&#39;)),<br>    (&#39;en&#39;, gettext_noop(&#39;English&#39;)),<br>    (&#39;fr&#39;, gettext_noop(&#39;Français&#39;)),<br>]</pre><h4>Strings targetting 🎯</h4><p>Now that the minimum configuration stuff is done ✅ , next step is modifying in the source code. We have to find every string target of translation and ‘mark’ it as translatable, This means in Django to wrapp every string with a translation marker. Here we deal with HTML templates and Python code differently (You may ask about Javascript code, we’ll cover that on a later separate tutorial 😉).</p><ul><li><strong>Python code 🐍</strong></li></ul><p>Specify a translation string by using the function gettext(). It’s convention to import this as a shorter alias, _, to save typing.</p><pre>from django.utils.translation import gettext as _<br><br>def someview(request):<br>  ...<br>  title = _(&quot;Foo bar baz title&quot;)<br>  ...</pre><p><em>gettext</em> is used when we need to get the translation immediately, otherwise it is a good practice to use <em>gettext_lazy</em></p><p><em>gettext_lazy</em> stores a lazy reference to the string — not the actual translation. The translation itself will be done when the string is used in a string context, such as in template rendering. Lazy evaluation can be explained quite simply as:</p><blockquote>Wait with evaluating value until it is needed</blockquote><ul><li><strong>HTML templates 📜</strong></li></ul><p>First we need to load i18n tag for every template, even if it extends a base template which has i18n already loaded. Then target a translatable string and mark it with <em>{% translate “foo bar baz” %} </em>template tag, if it contains no python expression (variable, function call …), or with <em>{% blocktranslate with some.context.variable as my_var %} foo bar baz string {{ my_var }} {% endblocktrans %}</em> when it contains nested (dot accessed) context variables or the string is too long to fit inside double quotes “” in one line. <em>trimmed</em> maybe useful to suppress leading and trailing whitespaces which reduces the size of the string. The following code snippets illustrates the concept</p><pre>{% load i18n %}<br>...<br>&lt;div class=&quot;container&quot;&gt;<br>...<br>  &lt;!-- Simple strings --&gt;<br>  &lt;h1&gt;<br>    {% translate &quot;Dummy title&quot; %}<br>  &lt;/h1&gt;<br><br>  &lt;!-- Strings with context variables --&gt;<br>  &lt;h1&gt;<br>    {% blocktranslate with user.username as username %}<br>      Welcome {{ username }}<br>    {% endblocktranslate %}<br>  &lt;/h1&gt;<br><br>  &lt;!-- Long strings trimmed to decrease size --&gt;<br>  &lt;p&gt;<br>    {% blocktranslate trimmed %}<br>      All work and no play makes Jack a dull boy,<br>      All play and no work makes Jack a mere toy.<br>    {% endblocktranslate %}<br>  &lt;/p&gt;<br>...<br>&lt;/div&gt;</pre><h4>Translation ✍️</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e2Y4di2QlmCeETgq" /><figcaption>Photo by <a href="https://unsplash.com/@edurnetx?utm_source=medium&amp;utm_medium=referral">Edurne Tx</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>After targetting all the translatable strings inside the source code, the next step is to extract those strings for each supported language into a <a href="https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html">Portable Object file (.po)</a>, later will be compiled into a <a href="https://www.gnu.org/software/gettext/manual/html_node/MO-Files.html">Machine Object file (.mo)</a> which is the file that Django loads translations from.</p><p>Each target language will have its own django.po file extracted under a directory named <strong><em>locale/LANG/LC_MESSAGES/</em></strong> inside the project’s root or the app root folder. First we create <strong><em>locale/</em></strong> directory in the app root folder</p><figure><img alt="folder structure" src="https://cdn-images-1.medium.com/max/464/1*k5NSybdqQrlSe79u2QE5zQ.png" /><figcaption>Folder structure</figcaption></figure><p>Next we make use of Django’s commands <strong><em>‘makemessages’</em></strong> and <strong><em>‘compilemessages’</em></strong> to generate messages files (django.po). These files are merely plain-text files representing each language and contains all available translation strings and how they should be represented in the given language. Let’s now create these magic files, we do that by running the following script</p><pre># Generate for all target languages<br>django-admin makemessages -a # or --all<br><br># Generate for one target language (eg: english)<br>django-admin makemessages -l en # or --locale en</pre><p>Messages files (.po) have the following content structure</p><pre>#: path/to/python/module.py:23<br>msgid &quot;Welcome to my site.&quot;<br>msgstr &quot;&quot;<br><br>#: path/to/html/template.hmtl:1337<br>msgid &quot;Dummy string&quot;<br>msgstr &quot;&quot;</pre><p>Now comes the translator’s job, each <em>msgid</em> in the po file needs an equivalent <em>msgstr</em> translation. after filling all the translations, the final step is to compile the message file into a .mo file which is a binary file optimized for use by gettext. For this purpose we run the following script</p><pre># Compile messages for all locales<br>django-admin compilemessages<br><br># Compile messages for a specific language (locale)<br>django-admin compilemessages -l en  # or --locale en</pre><p>I guess we are good to go, the changes will be reflected after restarting Django server. each time the server is restarted it loads the translations from the binary compiled files (.mo).</p><p>That’s it ! Very simple right !?<br>We made things easy on purpose, next article will be more in depth. We will go through some issues that are commonly encountered with i18n module, also we will be talking about Translation of Javascript files. And finally cover a proposed solution to automate the translator’s task and integrate that into Translation pipeline.</p><p>I hope you find this article useful and you enjoyed it, Feel free to leave comments on issues you faced, or any suggestion you may have. Follow me for more content like this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa368d21a133" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>