Switch to Django i18n for code strings

Django i18n layer is on top of gettext and provide may crucial features
such as per-request locales, lazy translations etc.
This commit is contained in:
Sunil Mohan Adapa 2015-11-13 22:08:43 +05:30
parent 02cd89b60d
commit 3df1a88824
65 changed files with 302 additions and 289 deletions

View File

@ -19,7 +19,7 @@
Python action utility functions. Python action utility functions.
""" """
from gettext import gettext as _ from django.utils.translation import ugettext as _
import psutil import psutil
import socket import socket
import subprocess import subprocess

View File

@ -16,14 +16,14 @@
# #
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
from plinth import cfg from plinth import cfg
def init(): def init():
"""Initailize the apps module""" """Initailize the apps module"""
cfg.main_menu.add_urlname("Apps", "glyphicon-download-alt", "apps:index", cfg.main_menu.add_urlname(_('Apps'), 'glyphicon-download-alt', 'apps:index',
80) 80)

View File

@ -19,7 +19,7 @@
Plinth module for service discovery. Plinth module for service discovery.
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
import subprocess import subprocess
from plinth import actions from plinth import actions

View File

@ -20,7 +20,7 @@ Plinth module for service discovery forms.
""" """
from django import forms from django import forms
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
class ServiceDiscoveryForm(forms.Form): class ServiceDiscoveryForm(forms.Form):

View File

@ -21,7 +21,7 @@ Plinth module for service discovery views.
from django.contrib import messages from django.contrib import messages
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext as _
import logging import logging
from .forms import ServiceDiscoveryForm from .forms import ServiceDiscoveryForm

View File

@ -23,7 +23,7 @@ from django import forms
from django.contrib import messages from django.contrib import messages
from django.core import validators from django.core import validators
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext as _, ugettext_lazy
import logging import logging
import socket import socket
@ -61,29 +61,33 @@ class ConfigurationForm(forms.Form):
"""Main system configuration form""" """Main system configuration form"""
# We're more conservative than RFC 952 and RFC 1123 # We're more conservative than RFC 952 and RFC 1123
hostname = TrimmedCharField( hostname = TrimmedCharField(
label=_('Hostname'), label=ugettext_lazy('Hostname'),
help_text=_('Your hostname is the local name by which other machines \ help_text=\
on your LAN can reach you. It must be alphanumeric, start with an alphabet \ ugettext_lazy('Your hostname is the local name by which other machines '
and must not be greater than 63 characters in length.'), 'on your LAN can reach you. It must be alphanumeric, '
'start with an alphabet and must not be greater than 63 '
'characters in length.'),
validators=[ validators=[
validators.RegexValidator(r'^[a-zA-Z][a-zA-Z0-9]{,62}$', validators.RegexValidator(r'^[a-zA-Z][a-zA-Z0-9]{,62}$',
_('Invalid hostname'))]) ugettext_lazy('Invalid hostname'))])
domainname = TrimmedCharField( domainname = TrimmedCharField(
label=_('Domain Name'), label=ugettext_lazy('Domain Name'),
help_text=_('Your domain name is the global name by which other \ help_text=\
machines on the Internet can reach you. It must consist of alphanumeric words \ ugettext_lazy('Your domain name is the global name by which other '
separated by dots.'), 'machines on the Internet can reach you. It must consist '
'of alphanumeric words separated by dots.'),
required=False, required=False,
validators=[ validators=[
validators.RegexValidator(r'^[a-zA-Z][a-zA-Z0-9.]*$', validators.RegexValidator(r'^[a-zA-Z][a-zA-Z0-9.]*$',
_('Invalid domain name'))]) ugettext_lazy('Invalid domain name'))])
def init(): def init():
"""Initialize the module""" """Initialize the module"""
menu = cfg.main_menu.get('system:index') menu = cfg.main_menu.get('system:index')
menu.add_urlname(_('Configure'), 'glyphicon-cog', 'config:index', 10) menu.add_urlname(ugettext_lazy('Configure'), 'glyphicon-cog',
'config:index', 10)
def index(request): def index(request):
@ -121,8 +125,8 @@ def _apply_changes(request, old_status, new_status):
try: try:
set_hostname(new_status['hostname']) set_hostname(new_status['hostname'])
except Exception as exception: except Exception as exception:
messages.error(request, _('Error setting hostname: %s') % messages.error(request, _('Error setting hostname: {exception}')
exception) .format(exception=exception))
else: else:
messages.success(request, _('Hostname set')) messages.success(request, _('Hostname set'))
else: else:
@ -132,8 +136,8 @@ def _apply_changes(request, old_status, new_status):
try: try:
set_domainname(new_status['domainname']) set_domainname(new_status['domainname'])
except Exception as exception: except Exception as exception:
messages.error(request, _('Error setting domain name: %s') % messages.error(request, _('Error setting domain name: {exception}')
exception) .format(exception=exception))
else: else:
messages.success(request, _('Domain name set')) messages.success(request, _('Domain name set'))
else: else:

View File

@ -19,7 +19,7 @@
Plinth module to configure system date and time Plinth module to configure system date and time
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
import subprocess import subprocess
from plinth import actions from plinth import actions

View File

@ -20,7 +20,7 @@ Forms for configuring date and time
""" """
from django import forms from django import forms
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
import glob import glob
import re import re

View File

@ -21,7 +21,7 @@ Plinth module for configuring date and time
from django.contrib import messages from django.contrib import messages
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext as _
import logging import logging
from .forms import DateTimeForm from .forms import DateTimeForm
@ -90,8 +90,8 @@ def _apply_changes(request, old_status, new_status):
try: try:
actions.superuser_run('timezone-change', [new_status['time_zone']]) actions.superuser_run('timezone-change', [new_status['time_zone']])
except Exception as exception: except Exception as exception:
messages.error(request, _('Error setting time zone: %s') % messages.error(request, _('Error setting time zone: {exception}')
exception) .format(exception=exception))
else: else:
messages.success(request, _('Time zone set')) messages.success(request, _('Time zone set'))

View File

@ -19,7 +19,7 @@
Plinth module to configure a Deluge web client. Plinth module to configure a Deluge web client.
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
from plinth import actions from plinth import actions
from plinth import action_utils from plinth import action_utils

View File

@ -20,7 +20,7 @@ Forms for configuring Deluge web client.
""" """
from django import forms from django import forms
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
class DelugeForm(forms.Form): class DelugeForm(forms.Form):

View File

@ -21,7 +21,7 @@ Plinth module to configure a Deluge web client.
from django.contrib import messages from django.contrib import messages
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext as _
from .forms import DelugeForm from .forms import DelugeForm
from plinth import actions from plinth import actions

View File

@ -23,7 +23,7 @@ import collections
from django.http import Http404 from django.http import Http404
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from django.views.decorators.http import require_POST from django.views.decorators.http import require_POST
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
import importlib import importlib
import logging import logging
import threading import threading
@ -42,8 +42,8 @@ _running_task = None
def init(): def init():
"""Initialize the module""" """Initialize the module"""
menu = cfg.main_menu.get('system:index') menu = cfg.main_menu.get('system:index')
menu.add_urlname("Diagnostics", "glyphicon-screenshot", menu.add_urlname(_('Diagnostics'), 'glyphicon-screenshot',
"diagnostics:index", 30) 'diagnostics:index', 30)
def index(request): def index(request):

View File

@ -19,44 +19,43 @@ from django import forms
from django.contrib import messages from django.contrib import messages
from django.core import validators from django.core import validators
from django.core.urlresolvers import reverse_lazy from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext as _, ugettext_lazy
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _
import logging import logging
from plinth import actions from plinth import actions
from plinth import cfg from plinth import cfg
from plinth import package from plinth import package
LOGGER = logging.getLogger(__name__) logger = logging.getLogger(__name__)
EMPTYSTRING = 'none' EMPTYSTRING = 'none'
subsubmenu = [{'url': reverse_lazy('dynamicdns:index'), subsubmenu = [{'url': reverse_lazy('dynamicdns:index'),
'text': _('About')}, 'text': ugettext_lazy('About')},
{'url': reverse_lazy('dynamicdns:configure'), {'url': reverse_lazy('dynamicdns:configure'),
'text': _('Configure')}, 'text': ugettext_lazy('Configure')},
{'url': reverse_lazy('dynamicdns:statuspage'), {'url': reverse_lazy('dynamicdns:statuspage'),
'text': _('Status')} 'text': ugettext_lazy('Status')}]
]
def init(): def init():
"""Initialize the dynamicdns module""" """Initialize the dynamicdns module"""
menu = cfg.main_menu.get('apps:index') menu = cfg.main_menu.get('apps:index')
menu.add_urlname('Dynamic DNS', 'glyphicon-refresh', menu.add_urlname(ugettext_lazy('Dynamic DNS'), 'glyphicon-refresh',
'dynamicdns:index', 500) 'dynamicdns:index', 500)
@package.required(['ez-ipupdate']) @package.required(['ez-ipupdate'])
def index(request): def index(request):
"""Serve dynamic DNS page""" """Serve Dynamic DNS page."""
return TemplateResponse(request, 'dynamicdns.html', return TemplateResponse(request, 'dynamicdns.html',
{'title': _('dynamicdns'), {'title': _('Dynamic DNS'),
'subsubmenu': subsubmenu}) 'subsubmenu': subsubmenu})
class TrimmedCharField(forms.CharField): class TrimmedCharField(forms.CharField):
"""Trim the contents of a CharField""" """Trim the contents of a CharField."""
def clean(self, value): def clean(self, value):
"""Clean and validate the field value""" """Clean and validate the field value"""
if value: if value:
@ -66,104 +65,99 @@ class TrimmedCharField(forms.CharField):
class ConfigureForm(forms.Form): class ConfigureForm(forms.Form):
"""Form to configure the dynamic DNS client""" """Form to configure the Dynamic DNS client."""
help_update_url = \
hlp_updt_url = 'The Variables <User>, <Pass>, <Ip>, \ ugettext_lazy('The Variables <User>, <Pass>, <Ip>, '
<Domain> may be used within the URL. For details\ '<Domain> may be used within the URL. For details '
see the update URL templates of the example providers.' 'see the update URL templates of the example providers.')
help_services = \
hlp_services = 'Please choose an update protocol according to your \ ugettext_lazy('Please choose an update protocol according to your '
provider. If your provider does not support the GnudIP \ 'provider. If your provider does not support the GnudIP '
protocol or your provider is not listed you may use \ 'protocol or your provider is not listed you may use the '
the update URL of your provider.' 'update URL of your provider.')
help_server = \
hlp_server = 'Please do not enter a URL here (like "https://example.com/")\ ugettext_lazy('Please do not enter a URL here (like '
but only the hostname of the GnuDIP server (like \ '"https://example.com/") but only the hostname of the '
"example.com").' 'GnuDIP server (like "example.pcom").')
help_domain = \
hlp_domain = 'The public domain name you want use to reach your box.' ugettext_lazy('The public domain name you want use to reach your box.')
help_disable_ssl = \
hlp_disable_ssl = 'Use this option if your provider uses self signed \ ugettext_lazy('Use this option if your provider uses self signed '
certificates.' 'certificates.')
help_http_auth = \
hlp_http_auth = 'If this option is selected, your username and \ ugettext_lazy('If this option is selected, your username and password '
password will be used for HTTP basic authentication.' 'will be used for HTTP basic authentication.')
help_secret = \
hlp_secret = 'Leave this field empty \ ugettext_lazy('Leave this field empty if you want to keep your '
if you want to keep your previous configured password.' 'previous configured password.')
help_ip_url = \
hlp_ipurl = 'Optional Value. If your FreedomBox is not connected \ ugettext_lazy('Optional Value. If your FreedomBox is not connected '
directly to the Internet (i.e. connected to a NAT \ 'directly to the Internet (i.e. connected to a NAT '
router) this URL is used to figure out the real Internet \ 'router) this URL is used to figure out the real '
IP. The URL should simply return the IP where the \ 'Internet IP. The URL should simply return the IP where'
client comes from. Example: \ 'the client comes from. Example: '
http://myip.datasystems24.de' 'http://myip.datasystems24.de')
help_user = \
hlp_user = 'You should have been requested to select a username \ ugettext_lazy('You should have been requested to select a username '
when you created the account.' 'when you created the account.')
"""ToDo: sync this list with the html template file""" """ToDo: sync this list with the html template file"""
provider_choices = ( provider_choices = (
('GnuDIP', 'GnuDIP'), ('GnuDIP', 'GnuDIP'),
('noip', 'noip.com'), ('noip', 'noip.com'),
('selfhost', 'selfhost.bz'), ('selfhost', 'selfhost.bz'),
('freedns', 'freedns.afraid.org'), ('freedns', 'freedns.afraid.org'),
('other', 'other update URL')) ('other', 'other update URL'))
enabled = forms.BooleanField(label=_('Enable Dynamic DNS'), enabled = forms.BooleanField(label=ugettext_lazy('Enable Dynamic DNS'),
required=False) required=False)
service_type = forms.ChoiceField(label=_('Service type'), service_type = forms.ChoiceField(label=ugettext_lazy('Service type'),
help_text=_(hlp_services), help_text=help_services,
choices=provider_choices) choices=provider_choices)
dynamicdns_server = TrimmedCharField( dynamicdns_server = TrimmedCharField(
label=_('GnudIP Server Address'), label=ugettext_lazy('GnudIP Server Address'),
required=False, required=False,
help_text=_(hlp_server), help_text=help_server,
validators=[ validators=[
validators.RegexValidator(r'^[\w-]{1,63}(\.[\w-]{1,63})*$', validators.RegexValidator(r'^[\w-]{1,63}(\.[\w-]{1,63})*$',
_('Invalid server name'))]) ugettext_lazy('Invalid server name'))])
dynamicdns_update_url = TrimmedCharField(label=_('Update URL'), dynamicdns_update_url = TrimmedCharField(
required=False, label=ugettext_lazy('Update URL'), required=False,
help_text=_(hlp_updt_url)) help_text=help_update_url)
disable_SSL_cert_check = forms.BooleanField(label=_('accept all SSL \ disable_SSL_cert_check = forms.BooleanField(
certificates'), label=ugettext_lazy('accept all SSL certificates'),
help_text=_(hlp_disable_ssl), help_text=help_disable_ssl, required=False)
required=False)
use_http_basic_auth = forms.BooleanField(label=_('use HTTP basic \ use_http_basic_auth = forms.BooleanField(
authentication'), label=ugettext_lazy('use HTTP basic authentication'),
help_text=_(hlp_http_auth), help_text=help_http_auth, required=False)
required=False)
dynamicdns_domain = TrimmedCharField( dynamicdns_domain = TrimmedCharField(
label=_('Domain Name'), label=ugettext_lazy('Domain Name'),
help_text=_(hlp_domain), help_text=help_domain,
required=False, required=False,
validators=[ validators=[
validators.RegexValidator(r'^[\w-]{1,63}(\.[\w-]{1,63})*$', validators.RegexValidator(r'^[\w-]{1,63}(\.[\w-]{1,63})*$',
_('Invalid domain name'))]) ugettext_lazy('Invalid domain name'))])
dynamicdns_user = TrimmedCharField( dynamicdns_user = TrimmedCharField(
label=_('Username'), label=ugettext_lazy('Username'), required=False, help_text=help_user)
required=False,
help_text=_(hlp_user))
dynamicdns_secret = TrimmedCharField( dynamicdns_secret = TrimmedCharField(
label=_('Password'), widget=forms.PasswordInput(), label=ugettext_lazy('Password'), widget=forms.PasswordInput(),
required=False, required=False, help_text=help_secret)
help_text=_(hlp_secret))
showpw = forms.BooleanField(label=_('show password'), showpw = forms.BooleanField(label=ugettext_lazy('show password'),
required=False) required=False)
dynamicdns_ipurl = TrimmedCharField( dynamicdns_ipurl = TrimmedCharField(
label=_('IP check URL'), label=ugettext_lazy('IP check URL'),
required=False, required=False,
help_text=_(hlp_ipurl), help_text=help_ip_url,
validators=[ validators=[
validators.URLValidator(schemes=['http', 'https', 'ftp'])]) validators.URLValidator(schemes=['http', 'https', 'ftp'])])
@ -177,35 +171,33 @@ class ConfigureForm(forms.Form):
service_type = cleaned_data.get('service_type') service_type = cleaned_data.get('service_type')
old_dynamicdns_secret = self.initial['dynamicdns_secret'] old_dynamicdns_secret = self.initial['dynamicdns_secret']
"""clear the fields which are not in use""" # Clear the fields which are not in use
if service_type == 'GnuDIP': if service_type == 'GnuDIP':
dynamicdns_update_url = "" dynamicdns_update_url = ''
else: else:
dynamicdns_server = "" dynamicdns_server = ''
if cleaned_data.get('enabled'): if cleaned_data.get('enabled'):
"""check if gnudip server or update URL is filled""" # Check if gnudip server or update URL is filled
if not dynamicdns_update_url and not dynamicdns_server: if not dynamicdns_update_url and not dynamicdns_server:
raise forms.ValidationError('please give update URL or \ raise forms.ValidationError(
a GnuDIP Server') _('Please provide update URL or a GnuDIP Server'))
LOGGER.info('no server address given')
if dynamicdns_server and not dynamicdns_user: if dynamicdns_server and not dynamicdns_user:
raise forms.ValidationError('please give GnuDIP username') raise forms.ValidationError(_('Please provide GnuDIP username'))
if dynamicdns_server and not dynamicdns_domain: if dynamicdns_server and not dynamicdns_domain:
raise forms.ValidationError('please give GnuDIP domain') raise forms.ValidationError(_('Please provide GnuDIP domain'))
"""check if a password was set before or a password is set now""" # Check if a password was set before or a password is set now
if (dynamicdns_server and not dynamicdns_secret if dynamicdns_server and \
and not old_dynamicdns_secret): not dynamicdns_secret and not old_dynamicdns_secret:
raise forms.ValidationError('please give a password') raise forms.ValidationError(_('Please provide a password'))
LOGGER.info('no password given')
@package.required(['ez-ipupdate']) @package.required(['ez-ipupdate'])
def configure(request): def configure(request):
"""Serve the configuration form""" """Serve the configuration form."""
status = get_status() status = get_status()
form = None form = None
@ -219,14 +211,14 @@ def configure(request):
form = ConfigureForm(initial=status) form = ConfigureForm(initial=status)
return TemplateResponse(request, 'dynamicdns_configure.html', return TemplateResponse(request, 'dynamicdns_configure.html',
{'title': _('Configure dynamicdns Client'), {'title': _('Configure Dynamic DNS'),
'form': form, 'form': form,
'subsubmenu': subsubmenu}) 'subsubmenu': subsubmenu})
@package.required(['ez-ipupdate']) @package.required(['ez-ipupdate'])
def statuspage(request): def statuspage(request):
"""Serve the status page """ """Serve the status page."""
check_nat = actions.run('dynamicdns', ['get-nat']) check_nat = actions.run('dynamicdns', ['get-nat'])
last_update = actions.run('dynamicdns', ['get-last-success']) last_update = actions.run('dynamicdns', ['get-last-success'])
@ -235,13 +227,13 @@ def statuspage(request):
timer = actions.run('dynamicdns', ['get-timer']) timer = actions.run('dynamicdns', ['get-timer'])
if no_nat: if no_nat:
LOGGER.info('we are not behind a NAT') logger.info('Not behind a NAT')
if nat_unchecked: if nat_unchecked:
LOGGER.info('we did not checked if we are behind a NAT') logger.info('Did not check if we are behind a NAT')
return TemplateResponse(request, 'dynamicdns_status.html', return TemplateResponse(request, 'dynamicdns_status.html',
{'title': _('Status of dynamicdns Client'), {'title': _('Status of Dynamic DNS'),
'no_nat': no_nat, 'no_nat': no_nat,
'nat_unchecked': nat_unchecked, 'nat_unchecked': nat_unchecked,
'timer': timer, 'timer': timer,
@ -250,8 +242,8 @@ def statuspage(request):
def get_status(): def get_status():
"""Return the current status""" """Return the current status."""
"""ToDo: use key/value instead of hard coded value list""" # TODO: use key/value instead of hard coded value list
status = {} status = {}
output = actions.run('dynamicdns', ['status']) output = actions.run('dynamicdns', ['status'])
details = output.split() details = output.split()
@ -269,7 +261,6 @@ def get_status():
if details[2] == 'disabled': if details[2] == 'disabled':
status['dynamicdns_domain'] = '' status['dynamicdns_domain'] = ''
else: else:
status['dynamicdns_domain'] = details[2]
status['dynamicdns_domain'] = details[2].replace("'", "") status['dynamicdns_domain'] = details[2].replace("'", "")
else: else:
status['dynamicdns_domain'] = '' status['dynamicdns_domain'] = ''
@ -327,9 +318,9 @@ def get_status():
def _apply_changes(request, old_status, new_status): def _apply_changes(request, old_status, new_status):
"""Apply the changes to Dynamic DNS client""" """Apply the changes to Dynamic DNS client."""
LOGGER.info('New status is - %s', new_status) logger.info('New status is - %s', new_status)
LOGGER.info('Old status was - %s', old_status) logger.info('Old status was - %s', old_status)
if new_status['dynamicdns_secret'] == '': if new_status['dynamicdns_secret'] == '':
new_status['dynamicdns_secret'] = old_status['dynamicdns_secret'] new_status['dynamicdns_secret'] = old_status['dynamicdns_secret']
@ -370,17 +361,17 @@ def _apply_changes(request, old_status, new_status):
if old_status['enabled']: if old_status['enabled']:
_run(['stop']) _run(['stop'])
if new_status['enabled']: if new_status['enabled']:
_run(['start']) _run(['start'])
messages.success(request, messages.success(request, _('Configuration updated'))
_('Dynamic DNS configuration is updated!'))
else: else:
LOGGER.info('nothing changed') logger.info('Nothing changed')
def _run(arguments, superuser=False, input=None): def _run(arguments, superuser=False, input=None):
"""Run a given command and raise exception if there was an error""" """Run a given command and raise exception if there was an error."""
command = 'dynamicdns' command = 'dynamicdns'
if superuser: if superuser:

View File

@ -20,7 +20,7 @@ Plinth module to configure a firewall
""" """
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
import logging import logging
from plinth import actions from plinth import actions

View File

@ -21,7 +21,7 @@ Forms for first boot module.
from django.contrib import auth from django.contrib import auth
from django.contrib import messages from django.contrib import messages
from gettext import gettext as _ from django.utils.translation import ugettext as _
from plinth import actions from plinth import actions
from plinth.errors import ActionError from plinth.errors import ActionError

View File

@ -19,8 +19,8 @@ from django.contrib.auth.models import User
from django.core.urlresolvers import reverse_lazy from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render_to_response from django.shortcuts import render_to_response
from django.template import RequestContext from django.template import RequestContext
from django.utils.translation import ugettext as _
from django.views.generic import CreateView, TemplateView from django.views.generic import CreateView, TemplateView
from gettext import gettext as _
from plinth import kvstore from plinth import kvstore
from plinth import network from plinth import network

View File

@ -23,6 +23,7 @@ import os
from gettext import gettext as _ from gettext import gettext as _
from django.http import Http404 from django.http import Http404
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _, ugettext_lazy
from stronghold.decorators import public from stronghold.decorators import public
from plinth import cfg, __version__ from plinth import cfg, __version__
@ -30,13 +31,14 @@ from plinth import cfg, __version__
def init(): def init():
"""Initialize the Help module""" """Initialize the Help module"""
menu = cfg.main_menu.add_urlname(_('Documentation'), 'glyphicon-book', menu = cfg.main_menu.add_urlname(ugettext_lazy('Documentation'),
'help:index', 101) 'glyphicon-book', 'help:index', 101)
menu.add_urlname(_('Where to Get Help'), 'glyphicon-search', menu.add_urlname(ugettext_lazy('Where to Get Help'), 'glyphicon-search',
'help:index_explicit', 5) 'help:index_explicit', 5)
menu.add_urlname(_('FreedomBox Manual'), 'glyphicon-info-sign', menu.add_urlname(ugettext_lazy('FreedomBox Manual'), 'glyphicon-info-sign',
'help:manual', 10) 'help:manual', 10)
menu.add_urlname(_('About'), 'glyphicon-star', 'help:about', 100) menu.add_urlname(ugettext_lazy('About'), 'glyphicon-star', 'help:about',
100)
@public @public
@ -50,7 +52,7 @@ def index(request):
def about(request): def about(request):
"""Serve the about page""" """Serve the about page"""
context = { context = {
'title': _('About the {box_name}').format(box_name=cfg.box_name), 'title': _('About {box_name}').format(box_name=cfg.box_name),
'version': __version__ 'version': __version__
} }
return TemplateResponse(request, 'help_about.html', context) return TemplateResponse(request, 'help_about.html', context)

View File

@ -19,7 +19,7 @@
Plinth module to configure ikiwiki Plinth module to configure ikiwiki
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
from plinth import actions from plinth import actions
from plinth import action_utils from plinth import action_utils

View File

@ -20,7 +20,7 @@ Forms for configuring ikiwiki
""" """
from django import forms from django import forms
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
class IkiwikiForm(forms.Form): class IkiwikiForm(forms.Form):

View File

@ -23,7 +23,7 @@ from django.contrib import messages
from django.core.urlresolvers import reverse_lazy from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect from django.shortcuts import redirect
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext as _, ugettext_lazy
from .forms import IkiwikiForm, IkiwikiCreateForm from .forms import IkiwikiForm, IkiwikiCreateForm
from plinth import actions from plinth import actions
@ -33,11 +33,11 @@ from plinth.modules import ikiwiki
subsubmenu = [{'url': reverse_lazy('ikiwiki:index'), subsubmenu = [{'url': reverse_lazy('ikiwiki:index'),
'text': _('Configure')}, 'text': ugettext_lazy('Configure')},
{'url': reverse_lazy('ikiwiki:manage'), {'url': reverse_lazy('ikiwiki:manage'),
'text': _('Manage')}, 'text': ugettext_lazy('Manage')},
{'url': reverse_lazy('ikiwiki:create'), {'url': reverse_lazy('ikiwiki:create'),
'text': _('Create')}] 'text': ugettext_lazy('Create')}]
def on_install(): def on_install():
@ -142,9 +142,10 @@ def _create_wiki(request, name, admin_name, admin_password):
['create-wiki', '--wiki_name', name, ['create-wiki', '--wiki_name', name,
'--admin_name', admin_name], '--admin_name', admin_name],
input=admin_password.encode()) input=admin_password.encode())
messages.success(request, _('Created wiki %s.') % name) messages.success(request, _('Created wiki {name}.').format(name=name))
except actions.ActionError as err: except actions.ActionError as error:
messages.error(request, _('Could not create wiki: %s') % err) messages.error(request, _('Could not create wiki: {error}')
.format(error=error))
def _create_blog(request, name, admin_name, admin_password): def _create_blog(request, name, admin_name, admin_password):
@ -155,9 +156,10 @@ def _create_blog(request, name, admin_name, admin_password):
['create-blog', '--blog_name', name, ['create-blog', '--blog_name', name,
'--admin_name', admin_name], '--admin_name', admin_name],
input=admin_password.encode()) input=admin_password.encode())
messages.success(request, _('Created blog %s.') % name) messages.success(request, _('Created blog {name}.').format(name=name))
except actions.ActionError as err: except actions.ActionError as error:
messages.error(request, _('Could not create blog: %s') % err) messages.error(request, _('Could not create blog: {error}')
.format(error=error))
def delete(request, name): def delete(request, name):
@ -169,9 +171,10 @@ def delete(request, name):
if request.method == 'POST': if request.method == 'POST':
try: try:
actions.superuser_run('ikiwiki', ['delete', '--name', name]) actions.superuser_run('ikiwiki', ['delete', '--name', name])
messages.success(request, _('%s deleted.') % name) messages.success(request, _('{name} deleted.').format(name=name))
except actions.ActionError as err: except actions.ActionError as error:
messages.error(request, _('Could not delete %s: %s') % (name, err)) messages.error(request, _('Could not delete {name}: {error}')
.format(name=name, error=error))
return redirect(reverse_lazy('ikiwiki:manage')) return redirect(reverse_lazy('ikiwiki:manage'))

View File

@ -19,7 +19,7 @@
Plinth module to configure Mumble server Plinth module to configure Mumble server
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
from plinth import actions from plinth import actions
from plinth import action_utils from plinth import action_utils

View File

@ -20,7 +20,7 @@ Forms for configuring Mumble
""" """
from django import forms from django import forms
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
class MumbleForm(forms.Form): class MumbleForm(forms.Form):

View File

@ -21,7 +21,7 @@ Plinth module for configuring Mumble Server
from django.contrib import messages from django.contrib import messages
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext as _
import logging import logging
from .forms import MumbleForm from .forms import MumbleForm

View File

@ -19,7 +19,7 @@
Plinth module to interface with network-manager Plinth module to interface with network-manager
""" """
from gettext import gettext as _ from django.utils.translation import ugettext as _
from logging import Logger from logging import Logger
import subprocess import subprocess

View File

@ -17,7 +17,7 @@
from django import forms from django import forms
from django.core import validators from django.core import validators
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
from plinth import network from plinth import network
import gi import gi
@ -30,8 +30,8 @@ def _get_interface_choices(device_type):
interfaces = network.get_interface_list(device_type) interfaces = network.get_interface_list(device_type)
choices = [('', _('-- select --'))] choices = [('', _('-- select --'))]
for interface, mac in interfaces.items(): for interface, mac in interfaces.items():
display_string = _('{interface} ({mac})').format(interface=interface, display_string = '{interface} ({mac})'.format(interface=interface,
mac=mac) mac=mac)
choices.append((interface, display_string)) choices.append((interface, display_string))
return choices return choices
@ -85,8 +85,9 @@ class AddPPPoEForm(forms.Form):
'to.')) 'to.'))
zone = forms.ChoiceField( zone = forms.ChoiceField(
label=_('Firewall Zone'), label=_('Firewall Zone'),
help_text=_('The firewall zone will control which services are \ help_text=_('The firewall zone will control which services are '
available over this interfaces. Select Internal only for trusted networks.'), 'available over this interfaces. Select Internal only '
'for trusted networks.'),
choices=[('external', 'External'), ('internal', 'Internal')]) choices=[('external', 'External'), ('internal', 'Internal')])
username = forms.CharField(label=_('Username')) username = forms.CharField(label=_('Username'))
password = forms.CharField(label=_('Password'), password = forms.CharField(label=_('Password'),

View File

@ -19,8 +19,8 @@ from django.contrib import messages
from django.core.urlresolvers import reverse_lazy from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect from django.shortcuts import redirect
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _, ugettext_lazy
from django.views.decorators.http import require_POST from django.views.decorators.http import require_POST
from gettext import gettext as _
from logging import Logger from logging import Logger
from .forms import (ConnectionTypeSelectForm, AddEthernetForm, AddPPPoEForm, from .forms import (ConnectionTypeSelectForm, AddEthernetForm, AddPPPoEForm,
@ -33,17 +33,18 @@ from plinth import package
logger = Logger(__name__) logger = Logger(__name__)
subsubmenu = [{'url': reverse_lazy('networks:index'), subsubmenu = [{'url': reverse_lazy('networks:index'),
'text': _('Network Connections')}, 'text': ugettext_lazy('Network Connections')},
{'url': reverse_lazy('networks:scan'), {'url': reverse_lazy('networks:scan'),
'text': _('Nearby Wi-Fi Networks')}, 'text': ugettext_lazy('Nearby Wi-Fi Networks')},
{'url': reverse_lazy('networks:add'), {'url': reverse_lazy('networks:add'),
'text': _('Add Connection')}] 'text': ugettext_lazy('Add Connection')}]
def init(): def init():
"""Initialize the Networks module.""" """Initialize the Networks module."""
menu = cfg.main_menu.get('system:index') menu = cfg.main_menu.get('system:index')
menu.add_urlname(_('Networks'), 'glyphicon-signal', 'networks:index', 18) menu.add_urlname(ugettext_lazy('Networks'), 'glyphicon-signal',
'networks:index', 18)
@package.required(['network-manager']) @package.required(['network-manager'])
@ -218,14 +219,16 @@ def activate(request, uuid):
try: try:
connection = network.activate_connection(uuid) connection = network.activate_connection(uuid)
name = connection.get_id() name = connection.get_id()
messages.success(request, _('Activated connection %s.') % name) messages.success(request, _('Activated connection {name}.')
.format(name=name))
except network.ConnectionNotFound: except network.ConnectionNotFound:
messages.error(request, _('Failed to activate connection: ' messages.error(request, _('Failed to activate connection: '
'Connection not found.')) 'Connection not found.'))
except network.DeviceNotFound as exception: except network.DeviceNotFound as exception:
name = exception.args[0].get_id() name = exception.args[0].get_id()
messages.error(request, _('Failed to activate connection %s: ' messages.error(request, _('Failed to activate connection {name}: '
'No suitable device is available.') % name) 'No suitable device is available.')
.format(name=name))
return redirect(reverse_lazy('networks:index')) return redirect(reverse_lazy('networks:index'))
@ -236,7 +239,8 @@ def deactivate(request, uuid):
try: try:
active_connection = network.deactivate_connection(uuid) active_connection = network.deactivate_connection(uuid)
name = active_connection.get_id() name = active_connection.get_id()
messages.success(request, _('Deactivated connection %s.') % name) messages.success(request, _('Deactivated connection {name}.')
.format(name=name))
except network.ConnectionNotFound: except network.ConnectionNotFound:
messages.error(request, _('Failed to de-activate connection: ' messages.error(request, _('Failed to de-activate connection: '
'Connection not found.')) 'Connection not found.'))
@ -378,7 +382,8 @@ def delete(request, uuid):
if request.method == 'POST': if request.method == 'POST':
try: try:
name = network.delete_connection(uuid) name = network.delete_connection(uuid)
messages.success(request, _('Connection %s deleted.') % name) messages.success(request, _('Connection {name} deleted.')
.format(name=name))
except network.ConnectionNotFound: except network.ConnectionNotFound:
messages.error(request, _('Failed to delete connection: ' messages.error(request, _('Failed to delete connection: '
'Connection not found.')) 'Connection not found.'))

View File

@ -19,7 +19,7 @@
Plinth module to configure OpenVPN server. Plinth module to configure OpenVPN server.
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
from plinth import actions from plinth import actions
from plinth import action_utils from plinth import action_utils

View File

@ -20,7 +20,7 @@ Plinth module for configuring OpenVPN.
""" """
from django import forms from django import forms
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
class OpenVpnForm(forms.Form): # pylint: disable=W0232 class OpenVpnForm(forms.Form): # pylint: disable=W0232

View File

@ -23,8 +23,8 @@ from django.contrib import messages
from django.http import HttpResponse from django.http import HttpResponse
from django.shortcuts import redirect from django.shortcuts import redirect
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django.views.decorators.http import require_POST from django.views.decorators.http import require_POST
from gettext import gettext as _
import logging import logging
from .forms import OpenVpnForm from .forms import OpenVpnForm

View File

@ -22,7 +22,7 @@ Plinth module for configuring ownCloud.
from django import forms from django import forms
from django.contrib import messages from django.contrib import messages
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
from plinth import actions from plinth import actions
from plinth import cfg from plinth import cfg

View File

@ -19,7 +19,7 @@
Plinth module to configure PageKite Plinth module to configure PageKite
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
from plinth import cfg from plinth import cfg
__all__ = ['init'] __all__ = ['init']

View File

@ -16,13 +16,12 @@
# #
import copy import copy
from gettext import gettext as _
import json
import logging
from django import forms from django import forms
from django.contrib import messages from django.contrib import messages
from django.core import validators from django.core import validators
from django.utils.translation import ugettext as _, ugettext_lazy
import json
import logging
from plinth.errors import ActionError from plinth.errors import ActionError
from . import utils from . import utils
@ -43,35 +42,38 @@ class TrimmedCharField(forms.CharField):
class ConfigurationForm(forms.Form): class ConfigurationForm(forms.Form):
"""Configure PageKite credentials and frontend""" """Configure PageKite credentials and frontend"""
enabled = forms.BooleanField(label=_('Enable PageKite'), required=False) enabled = forms.BooleanField(
label=ugettext_lazy('Enable PageKite'), required=False)
server_domain = forms.CharField( server_domain = forms.CharField(
label=_('Server domain'), required=False, label=ugettext_lazy('Server domain'), required=False,
help_text=_('Select your pagekite server. Set "pagekite.net" to ' help_text=\
'use the default pagekite.net server'), ugettext_lazy('Select your pagekite server. Set "pagekite.net" to use '
'the default pagekite.net server'),
widget=forms.TextInput()) widget=forms.TextInput())
server_port = forms.IntegerField( server_port = forms.IntegerField(
label=_('Server port'), required=False, label=ugettext_lazy('Server port'), required=False,
help_text=_('Port of your pagekite server (default: 80)')) help_text=ugettext_lazy('Port of your pagekite server (default: 80)'))
kite_name = TrimmedCharField( kite_name = TrimmedCharField(
label=_('Kite name'), label=ugettext_lazy('Kite name'),
help_text=_('Example: mybox.pagekite.me'), help_text=ugettext_lazy('Example: mybox.pagekite.me'),
validators=[ validators=[
validators.RegexValidator(r'^[\w-]{1,63}(\.[\w-]{1,63})*$', validators.RegexValidator(r'^[\w-]{1,63}(\.[\w-]{1,63})*$',
_('Invalid kite name'))]) ugettext_lazy('Invalid kite name'))])
kite_secret = TrimmedCharField( kite_secret = TrimmedCharField(
label=_('Kite secret'), label=ugettext_lazy('Kite secret'),
help_text=_('A secret associated with the kite or the default secret \ help_text=\
for your account if no secret is set on the kite')) ugettext_lazy('A secret associated with the kite or the default secret '
'for your account if no secret is set on the kite'))
def save(self, request): def save(self, request):
"""Save the form on submission after validation."""
old = self.initial old = self.initial
new = self.cleaned_data new = self.cleaned_data
LOGGER.info('New status is - %s', new) LOGGER.info('New status is - %s', new)
if old != new: if old != new:
config_changed = False config_changed = False
if old['kite_name'] != new['kite_name'] or \ if old['kite_name'] != new['kite_name'] or \
@ -136,14 +138,17 @@ class StandardServiceForm(forms.Form):
class BaseCustomServiceForm(forms.Form): class BaseCustomServiceForm(forms.Form):
"""Basic form functionality to handle a custom service""" """Basic form functionality to handle a custom service"""
choices = [("http", "http"), ("https", "https"), ("raw", "raw")] choices = [('http', 'http'), ('https', 'https'), ('raw', 'raw')]
protocol = forms.ChoiceField(choices=choices, label="protocol") protocol = forms.ChoiceField(
frontend_port = forms.IntegerField(min_value=0, max_value=65535, choices=choices, label=ugettext_lazy('protocol'))
label="external (frontend) port", frontend_port = forms.IntegerField(
required=True) min_value=0, max_value=65535,
backend_port = forms.IntegerField(min_value=0, max_value=65535, label=ugettext_lazy('external (frontend) port'), required=True)
label="internal (freedombox) port") backend_port = forms.IntegerField(
subdomains = forms.BooleanField(label="Enable Subdomains", required=False) min_value=0, max_value=65535,
label=ugettext_lazy('internal (freedombox) port'))
subdomains = forms.BooleanField(
label=ugettext_lazy('Enable Subdomains'), required=False)
def convert_formdata_to_service(self, formdata): def convert_formdata_to_service(self, formdata):
"""Add information to make a service out of the form data""" """Add information to make a service out of the form data"""
@ -210,8 +215,8 @@ class AddCustomServiceForm(BaseCustomServiceForm):
except KeyError: except KeyError:
is_predefined = False is_predefined = False
if is_predefined: if is_predefined:
msg = _("""This service is available as a standard service. Please msg = _('This service is available as a standard service. Please '
use the 'Standard Services' page to enable it.""") 'use the "Standard Services" page to enable it.')
raise forms.ValidationError(msg) raise forms.ValidationError(msg)
return cleaned_data return cleaned_data

View File

@ -15,7 +15,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
import json import json
import logging import logging
import os import os
@ -49,9 +49,9 @@ PREDEFINED_SERVICES = {
'backend_port': '80', 'backend_port': '80',
'backend_host': BACKEND_HOST, 'backend_host': BACKEND_HOST,
'secret': KITE_SECRET}, 'secret': KITE_SECRET},
'label': _("Web Server (HTTP)"), 'label': _('Web Server (HTTP)'),
'help_text': _("Site will be available at " 'help_text': _('Site will be available at '
"<a href=\"http://{0}\">http://{0}</a>"), '<a href=\"http://{0}\">http://{0}</a>'),
}, },
'https': { 'https': {
'params': {'protocol': 'https', 'params': {'protocol': 'https',
@ -59,9 +59,9 @@ PREDEFINED_SERVICES = {
'backend_port': '443', 'backend_port': '443',
'backend_host': BACKEND_HOST, 'backend_host': BACKEND_HOST,
'secret': KITE_SECRET}, 'secret': KITE_SECRET},
'label': _("Web Server (HTTPS)"), 'label': _('Web Server (HTTPS)'),
'help_text': _("Site will be available at " 'help_text': _('Site will be available at '
"<a href=\"https://{0}\">https://{0}</a>"), '<a href=\"https://{0}\">https://{0}</a>'),
}, },
'ssh': { 'ssh': {
'params': {'protocol': 'raw/22', 'params': {'protocol': 'raw/22',
@ -69,10 +69,10 @@ PREDEFINED_SERVICES = {
'backend_port': '22', 'backend_port': '22',
'backend_host': BACKEND_HOST, 'backend_host': BACKEND_HOST,
'secret': KITE_SECRET}, 'secret': KITE_SECRET},
'label': _("Secure Shell (SSH)"), 'label': _('Secure Shell (SSH)'),
'help_text': _("See SSH client setup <a href=\"" 'help_text': _('See SSH client setup <a href="'
"https://pagekite.net/wiki/Howto/SshOverPageKite/\">" 'https://pagekite.net/wiki/Howto/SshOverPageKite/">'
"instructions</a>") 'instructions</a>')
}, },
} }

View File

@ -15,11 +15,11 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from gettext import gettext as _
from django.core.urlresolvers import reverse, reverse_lazy from django.core.urlresolvers import reverse, reverse_lazy
from django.http.response import HttpResponseRedirect from django.http.response import HttpResponseRedirect
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _
from django.views.generic import View, TemplateView from django.views.generic import View, TemplateView
from django.views.generic.edit import FormView from django.views.generic.edit import FormView

View File

@ -19,7 +19,7 @@
Plinth module to configure Privoxy. Plinth module to configure Privoxy.
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
import json import json
from plinth import actions from plinth import actions

View File

@ -20,7 +20,7 @@ Forms for configuring Privoxy.
""" """
from django import forms from django import forms
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
class PrivoxyForm(forms.Form): class PrivoxyForm(forms.Form):

View File

@ -21,7 +21,7 @@ Plinth module for configuring Privoxy Server.
from django.contrib import messages from django.contrib import messages
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext as _
import logging import logging
from .forms import PrivoxyForm from .forms import PrivoxyForm

View File

@ -19,7 +19,7 @@
Plinth module to configure reStore Plinth module to configure reStore
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
from plinth import action_utils, cfg from plinth import action_utils, cfg
from plinth import service as service_module from plinth import service as service_module

View File

@ -20,7 +20,7 @@ Forms for configuring reStore.
""" """
from django import forms from django import forms
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
class ReStoreForm(forms.Form): class ReStoreForm(forms.Form):

View File

@ -17,7 +17,7 @@
from django.contrib import messages from django.contrib import messages
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext as _
from .forms import ReStoreForm from .forms import ReStoreForm
from plinth import actions, package from plinth import actions, package

View File

@ -19,7 +19,7 @@
Plinth module to configure Roundcube. Plinth module to configure Roundcube.
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
from plinth import actions from plinth import actions
from plinth import action_utils from plinth import action_utils

View File

@ -20,7 +20,7 @@ Forms for configuring Roundcube.
""" """
from django import forms from django import forms
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
class RoundcubeForm(forms.Form): class RoundcubeForm(forms.Form):

View File

@ -21,7 +21,7 @@ Plinth module for configuring Roundcube.
from django.contrib import messages from django.contrib import messages
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext as _
import logging import logging
from .forms import RoundcubeForm from .forms import RoundcubeForm

View File

@ -19,7 +19,7 @@
Plinth module to configure Shaarli. Plinth module to configure Shaarli.
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
from plinth import action_utils from plinth import action_utils
from plinth import cfg from plinth import cfg

View File

@ -20,7 +20,7 @@ Forms for configuring Shaarli.
""" """
from django import forms from django import forms
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
class ShaarliForm(forms.Form): class ShaarliForm(forms.Form):

View File

@ -21,7 +21,7 @@ Plinth module to configure Shaarli.
from django.contrib import messages from django.contrib import messages
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext as _
from .forms import ShaarliForm from .forms import ShaarliForm
from plinth import actions from plinth import actions

View File

@ -15,8 +15,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from gettext import gettext as _
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from django.utils.translation import ugettext_lazy as _
from plinth import cfg from plinth import cfg

View File

@ -19,7 +19,7 @@
Plinth module to configure Tor Plinth module to configure Tor
""" """
from gettext import gettext as _ from django.utils.translation import ugettext as _
from . import tor from . import tor
from .tor import init from .tor import init

View File

@ -23,7 +23,7 @@ import augeas
from django import forms from django import forms
from django.contrib import messages from django.contrib import messages
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
import glob import glob
import itertools import itertools

View File

@ -19,7 +19,7 @@
Plinth module to configure Transmission server Plinth module to configure Transmission server
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
from plinth import actions from plinth import actions
from plinth import action_utils from plinth import action_utils

View File

@ -20,7 +20,7 @@ Plinth module for configuring Transmission.
""" """
from django import forms from django import forms
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
class TransmissionForm(forms.Form): # pylint: disable=W0232 class TransmissionForm(forms.Form): # pylint: disable=W0232

View File

@ -21,7 +21,7 @@ Plinth module for configuring Transmission Server
from django.contrib import messages from django.contrib import messages
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext as _
import json import json
import logging import logging
import socket import socket

View File

@ -19,7 +19,7 @@
Plinth module for upgrades Plinth module for upgrades
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
from plinth import cfg from plinth import cfg

View File

@ -20,13 +20,13 @@ Forms for configuring unattended-upgrades.
""" """
from django import forms from django import forms
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
class ConfigureForm(forms.Form): class ConfigureForm(forms.Form):
"""Configuration form to enable/disable automatic upgrades.""" """Configuration form to enable/disable automatic upgrades."""
auto_upgrades_enabled = forms.BooleanField( auto_upgrades_enabled = forms.BooleanField(
label=_('Enable automatic upgrades'), required=False, label=_('Enable automatic upgrades'), required=False,
help_text=_('When enabled, the unattended-upgrades program will be \ help_text=_('When enabled, the unattended-upgrades program will be run '
run once per day. It will attempt to perform any package upgrades that are \ 'once per day. It will attempt to perform any package '
available.')) 'upgrades that are available.'))

View File

@ -22,8 +22,8 @@ Plinth module for upgrades
from django.contrib import messages from django.contrib import messages
from django.core.urlresolvers import reverse_lazy from django.core.urlresolvers import reverse_lazy
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _, ugettext_lazy
from django.views.decorators.http import require_POST from django.views.decorators.http import require_POST
from gettext import gettext as _
from .forms import ConfigureForm from .forms import ConfigureForm
from plinth import actions from plinth import actions
@ -31,9 +31,9 @@ from plinth import package
from plinth.errors import ActionError from plinth.errors import ActionError
subsubmenu = [{'url': reverse_lazy('upgrades:index'), subsubmenu = [{'url': reverse_lazy('upgrades:index'),
'text': _('Automatic Upgrades')}, 'text': ugettext_lazy('Automatic Upgrades')},
{'url': reverse_lazy('upgrades:upgrade'), {'url': reverse_lazy('upgrades:upgrade'),
'text': _('Upgrade Packages')}] 'text': ugettext_lazy('Upgrade Packages')}]
def on_install(): def on_install():
@ -114,8 +114,8 @@ def _apply_changes(request, old_status, new_status):
except ActionError as exception: except ActionError as exception:
error = exception.args[2] error = exception.args[2]
messages.error( messages.error(
request, _('Error when configuring unattended-upgrades: %s') % request, _('Error when configuring unattended-upgrades: {error}')
error) .format(error=error))
return return
if option == 'enable-auto': if option == 'enable-auto':

View File

@ -19,7 +19,7 @@
Plinth module to manage users Plinth module to manage users
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
import json import json
import subprocess import subprocess

View File

@ -19,7 +19,7 @@ from django import forms
from django.contrib import messages from django.contrib import messages
from django.contrib.auth.models import User, Group from django.contrib.auth.models import User, Group
from django.contrib.auth.forms import UserCreationForm, SetPasswordForm from django.contrib.auth.forms import UserCreationForm, SetPasswordForm
from gettext import gettext as _ from django.utils.translation import ugettext as _, ugettext_lazy
from plinth import actions from plinth import actions
from plinth.errors import ActionError from plinth.errors import ActionError
@ -38,16 +38,17 @@ class CreateUserForm(UserCreationForm):
groups = forms.MultipleChoiceField( groups = forms.MultipleChoiceField(
choices=GROUP_CHOICES, choices=GROUP_CHOICES,
label=_('Groups'), label=ugettext_lazy('Groups'),
required=False, required=False,
widget=forms.CheckboxSelectMultiple, widget=forms.CheckboxSelectMultiple,
help_text=_('Select which services should be available to the new ' help_text=\
'user. The user will be able to log in to services that ' ugettext_lazy('Select which services should be available to the new '
'support single sign-on through LDAP, if they are in the ' 'user. The user will be able to log in to services that '
'appropriate group.<br /><br />' 'support single sign-on through LDAP, if they are in the '
'Users in the admin group will be able to log in to all ' 'appropriate group.<br /><br />Users in the admin group '
'services. They can also log in to the system through SSH ' 'will be able to log in to all services. They can also '
'and have administrative privileges (sudo).')) 'log in to the system through SSH and have '
'administrative privileges (sudo).'))
def __init__(self, request, *args, **kwargs): def __init__(self, request, *args, **kwargs):
"""Initialize the form with extra request argument.""" """Initialize the form with extra request argument."""
@ -76,7 +77,8 @@ class CreateUserForm(UserCreationForm):
except ActionError: except ActionError:
messages.error( messages.error(
self.request, self.request,
_('Failed to add new user to %s group.') % group) _('Failed to add new user to {group} group.')
.format(group=group))
group_object, created = Group.objects.get_or_create(name=group) group_object, created = Group.objects.get_or_create(name=group)
group_object.user_set.add(user) group_object.user_set.add(user)

View File

@ -23,7 +23,7 @@ from django.core.urlresolvers import reverse, reverse_lazy
from django.views.generic.edit import (CreateView, DeleteView, UpdateView, from django.views.generic.edit import (CreateView, DeleteView, UpdateView,
FormView) FormView)
from django.views.generic import ListView from django.views.generic import ListView
from gettext import gettext as _ from django.utils.translation import ugettext as _, ugettext_lazy
from .forms import CreateUserForm, UserChangePasswordForm, UserUpdateForm from .forms import CreateUserForm, UserChangePasswordForm, UserUpdateForm
from plinth import actions from plinth import actions
@ -31,9 +31,9 @@ from plinth.errors import ActionError
subsubmenu = [{'url': reverse_lazy('users:index'), subsubmenu = [{'url': reverse_lazy('users:index'),
'text': _('Users')}, 'text': ugettext_lazy('Users')},
{'url': reverse_lazy('users:create'), {'url': reverse_lazy('users:create'),
'text': _('Create User')}] 'text': ugettext_lazy('Create User')}]
class ContextMixin(object): class ContextMixin(object):
@ -51,9 +51,9 @@ class UserCreate(ContextMixin, SuccessMessageMixin, CreateView):
form_class = CreateUserForm form_class = CreateUserForm
template_name = 'users_create.html' template_name = 'users_create.html'
model = User model = User
success_message = _('User %(username)s created.') success_message = ugettext_lazy('User %(username)s created.')
success_url = reverse_lazy('users:create') success_url = reverse_lazy('users:create')
title = _('Create User') title = ugettext_lazy('Create User')
def get_form_kwargs(self): def get_form_kwargs(self):
"""Make the request object available to the form.""" """Make the request object available to the form."""
@ -66,7 +66,7 @@ class UserList(ContextMixin, ListView):
"""View to list users.""" """View to list users."""
model = User model = User
template_name = 'users_list.html' template_name = 'users_list.html'
title = _('Users') title = ugettext_lazy('Users')
class UserUpdate(ContextMixin, SuccessMessageMixin, UpdateView): class UserUpdate(ContextMixin, SuccessMessageMixin, UpdateView):
@ -75,8 +75,8 @@ class UserUpdate(ContextMixin, SuccessMessageMixin, UpdateView):
model = User model = User
form_class = UserUpdateForm form_class = UserUpdateForm
slug_field = 'username' slug_field = 'username'
success_message = _('User %(username)s updated.') success_message = ugettext_lazy('User %(username)s updated.')
title = _('Edit User') title = ugettext_lazy('Edit User')
def get_form_kwargs(self): def get_form_kwargs(self):
"""Make the requst object available to the form.""" """Make the requst object available to the form."""
@ -100,7 +100,7 @@ class UserDelete(ContextMixin, DeleteView):
model = User model = User
slug_field = 'username' slug_field = 'username'
success_url = reverse_lazy('users:index') success_url = reverse_lazy('users:index')
title = _('Delete User') title = ugettext_lazy('Delete User')
def delete(self, *args, **kwargs): def delete(self, *args, **kwargs):
"""Set the success message of deleting the user. """Set the success message of deleting the user.
@ -110,7 +110,7 @@ class UserDelete(ContextMixin, DeleteView):
""" """
output = super(UserDelete, self).delete(*args, **kwargs) output = super(UserDelete, self).delete(*args, **kwargs)
message = _('User %s deleted.') % self.kwargs['slug'] message = _('User {user} deleted.').format(user=self.kwargs['slug'])
messages.success(self.request, message) messages.success(self.request, message)
try: try:
@ -126,8 +126,8 @@ class UserChangePassword(ContextMixin, SuccessMessageMixin, FormView):
"""View to change user password.""" """View to change user password."""
template_name = 'users_change_password.html' template_name = 'users_change_password.html'
form_class = UserChangePasswordForm form_class = UserChangePasswordForm
title = _('Change Password') title = ugettext_lazy('Change Password')
success_message = _('Password changed successfully.') success_message = ugettext_lazy('Password changed successfully.')
def get_form_kwargs(self): def get_form_kwargs(self):
"""Make the user object available to the form.""" """Make the user object available to the form."""

View File

@ -19,7 +19,7 @@
Plinth module to configure XMPP server Plinth module to configure XMPP server
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
import json import json
from plinth import actions from plinth import actions

View File

@ -20,7 +20,7 @@ Forms for configuring XMPP service.
""" """
from django import forms from django import forms
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
class XmppForm(forms.Form): # pylint: disable=W0232 class XmppForm(forms.Form): # pylint: disable=W0232

View File

@ -21,7 +21,7 @@ Plinth module to configure XMPP server
from django.contrib import messages from django.contrib import messages
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from gettext import gettext as _ from django.utils.translation import ugettext as _
import logging import logging
import socket import socket

View File

@ -20,6 +20,7 @@ Helper functions for working with network manager.
""" """
import collections import collections
from django.utils.translation import ugettext_lazy as _
import gi import gi
gi.require_version('GLib', '2.0') gi.require_version('GLib', '2.0')
from gi.repository import GLib as glib from gi.repository import GLib as glib
@ -35,9 +36,9 @@ import uuid
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
CONNECTION_TYPE_NAMES = collections.OrderedDict([ CONNECTION_TYPE_NAMES = collections.OrderedDict([
('802-3-ethernet', 'Ethernet'), ('802-3-ethernet', _('Ethernet')),
('802-11-wireless', 'Wi-Fi'), ('802-11-wireless', _('Wi-Fi')),
('pppoe', 'PPPoE') ('pppoe', _('PPPoE'))
]) ])

View File

@ -20,8 +20,8 @@ Framework for installing and updating distribution packages
""" """
from django.contrib import messages from django.contrib import messages
from django.utils.translation import ugettext as _
import functools import functools
from gettext import gettext as _
import gi import gi
gi.require_version('GLib', '2.0') gi.require_version('GLib', '2.0')
from gi.repository import GLib as glib from gi.repository import GLib as glib

View File

@ -19,7 +19,7 @@
Framework for working with servers and their services. Framework for working with servers and their services.
""" """
from gettext import gettext as _ from django.utils.translation import ugettext_lazy as _
import collections import collections
@ -35,7 +35,6 @@ class Service(object):
containing information such as current status and ports required containing information such as current status and ports required
for operation. for operation.
""" """
def __init__(self, service_id, name, ports=None, is_external=False, def __init__(self, service_id, name, ports=None, is_external=False,
enabled=True): enabled=True):
if not ports: if not ports: