Django i18n: is there a gettext alternative? - python

I'm looking for a way to translate my Django project. Built in mechanism provided with Django is great, but has several weak points which made me go looking for an alternative.
Project owner must be able to edit every translation including English (original translation). With gettext it is possible to edit translations with tools like Pootle, but the original strings stay hardcoded inside file sources or templates. There is no way that product owner can change them.
Possible solution is to make gettext translate some unique identifiers, and just translate them to all languages including English, like this:
_('form_sumbit_button')
But this makes tools like pootle almost impossible to use for translators.
Question: are there any tools for Django project translation that could fit my needs?

If you use some message IDs, they would either be incomprehensible ("message_2215") or you'd be forced to synchronise the message IDs to the actual messages ("Please press any key" = "please_press_any_key" => "Any key to continue" = "any_key_to_continue"). Either way, real strings are better for the programmers and for the tools.
However, if you employ a separate proof-reader for your strings, you can do the following:
Create an English "translation" file (yes, this works)
Let your proof-reader "translate" from English to English using Pootle or any other tool
Make sure your programmers keep that translation file untranslated by updating the strings in code.
(optional) Create a way to deploy translations independently of your main code so you can fix a typo quickly.

You may be able to use Pootle with the _("message_id") approach, depending on how easy Pootle is to customise (I don't know the internals so I can't say, but IIUC it uses Django where template changes are usually straightforward).
For example, Pootle's translation screens have "Original" and "Translation" sections; you could perhaps adapt the templates to show, under the "Original" section, a "Reference" section which displays some canonical translation using a specific reference language (e.g. English).
Or you may be able to use Pootle's alternative source language functionality, without needing to customise Pootle. You could store the canonical versions of the translations using an unused language code (or a made-up one).

Using identifiers is definitely possible with Gettext and there are tools which support this. However it might be unusual for some translators as they are used to downloading only .po file for offline translation, what does not work with monolingual translations.
For example Weblate supports monolingual Gettext files just fine (I'm author of this tool): https://docs.weblate.org/en/latest/formats.html#monolingual-gettext

Related

Repository pattern on Python

I'm new to python and I'm comming from the c# world.
Over there it seemed like the repository pattern was the way to go, but I am having trouble finding any tutorials of how to best do this on Python.
edit I understand that it can be implemented, I'm just wondering if there is any reason why I am finding close to nothing for how to go about doing this.
Thanks!
I wasn't immediately familiar with the "repository pattern", so I looked it up. It appears to be the idea of putting a more general API, like a dictionary-like key/value lookup, in front of a database or other data store. It seems that the idea is to add an additional layer of abstraction that can allow multiple types of data sources (like both a relational database and a CVS file) to be accessed transparently via a common API.
Given this definition, I can think of no reason why this design pattern wouldn't be equally applicable to a problem addressed with Python vs any other programming language.

How do I save code snippets to a database?

I'm creating a Django website for game developers to share code, which means I need to be able to save properly formatted code to a database, as well as being able to retrieve and display it.
Is there anything built into Django for this, or do I need to use a third party library?
I've played with a Django pagedown widget, which is modeled after StackOverflow's markdown editor, but I've had some trouble with it, and I'm not positive if that's is going to accomplish everything I want by itself.
Has anyone actually used the pagedown widget, implemented functionality similar to this, or know of another library that would work?
For storing the code, you can use any database that supports text types. That is, you would use a TextField in your model.
Now you need to decide how that raw text will be displayed/formatted.
This depends on what you mean by displaying properly formatted code, but I'm going to go ahead and just say you should check out Pygments. It is a syntax highlighting library that can be easily used w/Django.
Pygments works by your specifying a lexer (read: language) for it to apply styling to the target text. Whitespace will be preserved by your database. Everything else formatting-related is purely subjective. You'd presumably specify a fixed width font, a size, etc in the view and pass it to the context as you would any other DB-backed object.
Django Rest Framework's tutorial actually makes something very similar to what you are describing and uses Pygments, so I'd recommend checking that out for concrete usage examples.
For formatting code exclusively, I would avoid any markdown flavors like the one you listed, as code could contain characters that have special meaning in markdown, thus you would need to escape the text, and that defeats the purpose of markdown.

What is the best way of including common content (for example header script) in django / python web app

In php files, this task may be a simple include of another file but I wondered if it was similar practice in Django? like described here: https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#include
Short answer: No, Python doesn't perform that way.
Here's a long one:
A little bit about difference between PHP and Python web development
First of all, include and require are parts of PHP language itself. It means that before processing source code PHP interpreter includes source code from files given as arguments to those functions and then makes interpreting. That's the inheritance of the main purpose of PHP design (HTML, or, generally, text preprocessing).
Web development in Python is a bit different. Language itself was designed as general purpose programming language, so it doesn't assume text-processing by default. Code is just executed. That's why web development is usually done using frameworks (or wsgi modules if you prefer doing everything from scratch.
All that above means that all text manipulations (all output you generate, you generally do manually by creating result text string (or strings list when used with buffering) and giving the output result yourself.
Template languages
That's kinda messy point from which template languages were born, becoming essential part of every (or almost every) web application written in Python (you can assume something simalar to Smarty in PHP world). There are a lot of them: jinja, jinja2, mako, chameleon ... and many others. All of them are different but serve the same purpose (easyfying text generation via providing templates with placeholders for data of basic representation logic).
And here comes the main feature of Python web frameworks: application logic and representation are strictly splitted.
Here we came to the substance of your question:
As all of those template libraries providing text templating facilities are different, there's no common way to make PHP-like includes that we can say they are general for Python. Each of those tools provide different ways and philosophy of handling, in particular, includes, mainly divided into two mainstream ways:
macros- and slots-based (Chameleon)
template inheritance-based (Jinja2, Django template language)
All you need is to take one that best fits your needs (whether you like/unlike their syntax, some of them are faster, some are more readable, and so on..) and work with it combining with other tools that provide logic for your application.
Getting closer: About Django
It's common to use include template tag when you want to include some re-used part of application (e.g. pagination widget), for which you've adapted your view context.
But when you have common header for all pages, or another common part, it's better to use inheritance, that's achieved in two steps:
Basic template is created (containing general header and footer)
Specific templates are created via template inheritance feature, in particular, extends template tag in Django
Python is not PHP!
Django doesn't allow you to write arbitrary scripts(code) in templates. You should do all the computations/business tasks in views.py (controller) and pass results into template. In template usually you iterate over your result set and display data. In django 1.4 a new assignment tag was added , so you can do
{% get_movie_tickets_for_theater movie theater as tickets %}
but your get_movie_tickets_for_theater will be defined in templatetags python file.

Some questions about Django localisation

I intend to localise my Django application and began reading up on localisation on the Django site. This put a few questions in my mind:
It seems that when you run the 'django-admin.py makemessages' command, it scans the files for embedded strings and generates a message file that contains the translations. These translations are mapped to the strings in the file. For example, if I have a string in HTML that reads "Please enter the recipients name", Django would consider it to be the message id. What would happen if i changed something in the string. Let's say I added the missing apostrophe to the word "recipient". Would this break the translation?
In relation to the above scenario, Is it better to use full fledged sentences in the source (which might change) or would I be better off using a word like "RECIPIENT_NAME" which is less likely to change and easier to map to?
Does the 'django-admin.py makemessages' command scan the Python sources as well?
Thanks.
It very probably would, in some cases 'similar' strings can be detected and your translation will be marked with fuzzy. But it depends on the type of string, I don't know what adding an apostrophe would do. Read the GNU gettext docs for more information about this.
However, an easy solution for your problem would be: don't fix the typo in the original, but make a translation like english to english where the translated string is the correct one :). I personally wouldn't recommend this approach, but If you're afraid to break tens of translation files, it can be considered.
No it isn't, it throws away all sense of context. It might look clearer for sites where only a few translation strings are required and you know the exact context by heart. But as soon as you have 100s of strings in the translation file, short names like that will say nothing, you'll always have to look up the exact context. Even worse, it can be you use the same 'short name' for something that actually has to be translated differently, which will end up giving you weirder short names to handle both cases. Finally, if you use one normal language as default, you don't need to translate this language explicitly anymore.
Yes it does, there exist multiple functions to mark strings in python for translation, an overview can be found here.

Embedding Python code as a preprocessor PHP style

I'm going back over an old project where I added preprocessor functionality to Essence' and I realised that my previous solution of writing a domain specific language and associated lexer/parser was overkill.
Instead I just need to be able to embed dynamic language code into the file, isolate it at runtime, eval and insert the results. In other words very similar to the PHP model of inserting dynamic code into HTML. I'd rather not use PHP as Python is much easier to distribute as part of a larger project (IronPython or Jython)
So the question goes, how best to implement something like the following:
<code>Python goes here</code>
Lots of essence <code>Python</code> prime code goes here
I don't want to have to alter the structure of the Essence' file (if I remove all the code blocks everything left should be able to be syntactically correct. It needs to be able to insert text in place of a code block like PHP.
Finally security wise I'm not bothered about code injection, as it would be the user themselves choosing the file to execute although if there were security benefits to one model over another with no extra costs that would obviously be good.
Cheers in advance
Your best bet is to use one of the already made (and battle tested) Templating Engines. The two big ones that I've used are Mako, and Cheetah. They allow you to embed code right in the page, and are mostly used as the View in an MVC architecture.
If you feel that using one of those engines is overkill for your project, here is a small tutorial on how to implement basic templates yourself. Keep in mind that the example will need to be modified to suit your particular project/needs.

Categories

Resources