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.
"""
from gettext import gettext as _
from django.utils.translation import ugettext as _
import psutil
import socket
import subprocess

View File

@ -16,14 +16,14 @@
#
from django.template.response import TemplateResponse
from gettext import gettext as _
from django.utils.translation import ugettext_lazy as _
from plinth import cfg
def init():
"""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)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -19,7 +19,7 @@
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 action_utils

View File

@ -20,7 +20,7 @@ Forms for configuring Deluge web client.
"""
from django import forms
from gettext import gettext as _
from django.utils.translation import ugettext_lazy as _
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.template.response import TemplateResponse
from gettext import gettext as _
from django.utils.translation import ugettext as _
from .forms import DelugeForm
from plinth import actions

View File

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

View File

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

View File

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

View File

@ -21,7 +21,7 @@ Forms for first boot module.
from django.contrib import auth
from django.contrib import messages
from gettext import gettext as _
from django.utils.translation import ugettext as _
from plinth import actions
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.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _
from django.views.generic import CreateView, TemplateView
from gettext import gettext as _
from plinth import kvstore
from plinth import network

View File

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

View File

@ -19,7 +19,7 @@
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 action_utils

View File

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

View File

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

View File

@ -19,7 +19,7 @@
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 action_utils

View File

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

View File

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

View File

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

View File

@ -17,7 +17,7 @@
from django import forms
from django.core import validators
from gettext import gettext as _
from django.utils.translation import ugettext_lazy as _
from plinth import network
import gi
@ -30,8 +30,8 @@ def _get_interface_choices(device_type):
interfaces = network.get_interface_list(device_type)
choices = [('', _('-- select --'))]
for interface, mac in interfaces.items():
display_string = _('{interface} ({mac})').format(interface=interface,
mac=mac)
display_string = '{interface} ({mac})'.format(interface=interface,
mac=mac)
choices.append((interface, display_string))
return choices
@ -85,8 +85,9 @@ class AddPPPoEForm(forms.Form):
'to.'))
zone = forms.ChoiceField(
label=_('Firewall Zone'),
help_text=_('The firewall zone will control which services are \
available over this interfaces. Select Internal only for trusted networks.'),
help_text=_('The firewall zone will control which services are '
'available over this interfaces. Select Internal only '
'for trusted networks.'),
choices=[('external', 'External'), ('internal', 'Internal')])
username = forms.CharField(label=_('Username'))
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.shortcuts import redirect
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _, ugettext_lazy
from django.views.decorators.http import require_POST
from gettext import gettext as _
from logging import Logger
from .forms import (ConnectionTypeSelectForm, AddEthernetForm, AddPPPoEForm,
@ -33,17 +33,18 @@ from plinth import package
logger = Logger(__name__)
subsubmenu = [{'url': reverse_lazy('networks:index'),
'text': _('Network Connections')},
'text': ugettext_lazy('Network Connections')},
{'url': reverse_lazy('networks:scan'),
'text': _('Nearby Wi-Fi Networks')},
'text': ugettext_lazy('Nearby Wi-Fi Networks')},
{'url': reverse_lazy('networks:add'),
'text': _('Add Connection')}]
'text': ugettext_lazy('Add Connection')}]
def init():
"""Initialize the Networks module."""
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'])
@ -218,14 +219,16 @@ def activate(request, uuid):
try:
connection = network.activate_connection(uuid)
name = connection.get_id()
messages.success(request, _('Activated connection %s.') % name)
messages.success(request, _('Activated connection {name}.')
.format(name=name))
except network.ConnectionNotFound:
messages.error(request, _('Failed to activate connection: '
'Connection not found.'))
except network.DeviceNotFound as exception:
name = exception.args[0].get_id()
messages.error(request, _('Failed to activate connection %s: '
'No suitable device is available.') % name)
messages.error(request, _('Failed to activate connection {name}: '
'No suitable device is available.')
.format(name=name))
return redirect(reverse_lazy('networks:index'))
@ -236,7 +239,8 @@ def deactivate(request, uuid):
try:
active_connection = network.deactivate_connection(uuid)
name = active_connection.get_id()
messages.success(request, _('Deactivated connection %s.') % name)
messages.success(request, _('Deactivated connection {name}.')
.format(name=name))
except network.ConnectionNotFound:
messages.error(request, _('Failed to de-activate connection: '
'Connection not found.'))
@ -378,7 +382,8 @@ def delete(request, uuid):
if request.method == 'POST':
try:
name = network.delete_connection(uuid)
messages.success(request, _('Connection %s deleted.') % name)
messages.success(request, _('Connection {name} deleted.')
.format(name=name))
except network.ConnectionNotFound:
messages.error(request, _('Failed to delete connection: '
'Connection not found.'))

View File

@ -19,7 +19,7 @@
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 action_utils

View File

@ -20,7 +20,7 @@ Plinth module for configuring OpenVPN.
"""
from django import forms
from gettext import gettext as _
from django.utils.translation import ugettext_lazy as _
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.shortcuts import redirect
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django.views.decorators.http import require_POST
from gettext import gettext as _
import logging
from .forms import OpenVpnForm

View File

@ -22,7 +22,7 @@ Plinth module for configuring ownCloud.
from django import forms
from django.contrib import messages
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 cfg

View File

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

View File

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

View File

@ -15,7 +15,7 @@
# 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 logging
import os
@ -49,9 +49,9 @@ PREDEFINED_SERVICES = {
'backend_port': '80',
'backend_host': BACKEND_HOST,
'secret': KITE_SECRET},
'label': _("Web Server (HTTP)"),
'help_text': _("Site will be available at "
"<a href=\"http://{0}\">http://{0}</a>"),
'label': _('Web Server (HTTP)'),
'help_text': _('Site will be available at '
'<a href=\"http://{0}\">http://{0}</a>'),
},
'https': {
'params': {'protocol': 'https',
@ -59,9 +59,9 @@ PREDEFINED_SERVICES = {
'backend_port': '443',
'backend_host': BACKEND_HOST,
'secret': KITE_SECRET},
'label': _("Web Server (HTTPS)"),
'help_text': _("Site will be available at "
"<a href=\"https://{0}\">https://{0}</a>"),
'label': _('Web Server (HTTPS)'),
'help_text': _('Site will be available at '
'<a href=\"https://{0}\">https://{0}</a>'),
},
'ssh': {
'params': {'protocol': 'raw/22',
@ -69,10 +69,10 @@ PREDEFINED_SERVICES = {
'backend_port': '22',
'backend_host': BACKEND_HOST,
'secret': KITE_SECRET},
'label': _("Secure Shell (SSH)"),
'help_text': _("See SSH client setup <a href=\""
"https://pagekite.net/wiki/Howto/SshOverPageKite/\">"
"instructions</a>")
'label': _('Secure Shell (SSH)'),
'help_text': _('See SSH client setup <a href="'
'https://pagekite.net/wiki/Howto/SshOverPageKite/">'
'instructions</a>')
},
}

View File

@ -15,11 +15,11 @@
# 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.http.response import HttpResponseRedirect
from django.template.response import TemplateResponse
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.edit import FormView

View File

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

View File

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

View File

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

View File

@ -19,7 +19,7 @@
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 service as service_module

View File

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

View File

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

View File

@ -19,7 +19,7 @@
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 action_utils

View File

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

View File

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

View File

@ -19,7 +19,7 @@
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 cfg

View File

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

View File

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

View File

@ -15,8 +15,8 @@
# 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.utils.translation import ugettext_lazy as _
from plinth import cfg

View File

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

View File

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

View File

@ -19,7 +19,7 @@
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 action_utils

View File

@ -20,7 +20,7 @@ Plinth module for configuring Transmission.
"""
from django import forms
from gettext import gettext as _
from django.utils.translation import ugettext_lazy as _
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.template.response import TemplateResponse
from gettext import gettext as _
from django.utils.translation import ugettext as _
import json
import logging
import socket

View File

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

View File

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

View File

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

View File

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

View File

@ -19,7 +19,7 @@ from django import forms
from django.contrib import messages
from django.contrib.auth.models import User, Group
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.errors import ActionError
@ -38,16 +38,17 @@ class CreateUserForm(UserCreationForm):
groups = forms.MultipleChoiceField(
choices=GROUP_CHOICES,
label=_('Groups'),
label=ugettext_lazy('Groups'),
required=False,
widget=forms.CheckboxSelectMultiple,
help_text=_('Select which services should be available to the new '
'user. The user will be able to log in to services that '
'support single sign-on through LDAP, if they are in the '
'appropriate group.<br /><br />'
'Users in the admin group will be able to log in to all '
'services. They can also log in to the system through SSH '
'and have administrative privileges (sudo).'))
help_text=\
ugettext_lazy('Select which services should be available to the new '
'user. The user will be able to log in to services that '
'support single sign-on through LDAP, if they are in the '
'appropriate group.<br /><br />Users in the admin group '
'will be able to log in to all services. They can also '
'log in to the system through SSH and have '
'administrative privileges (sudo).'))
def __init__(self, request, *args, **kwargs):
"""Initialize the form with extra request argument."""
@ -76,7 +77,8 @@ class CreateUserForm(UserCreationForm):
except ActionError:
messages.error(
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.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,
FormView)
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 plinth import actions
@ -31,9 +31,9 @@ from plinth.errors import ActionError
subsubmenu = [{'url': reverse_lazy('users:index'),
'text': _('Users')},
'text': ugettext_lazy('Users')},
{'url': reverse_lazy('users:create'),
'text': _('Create User')}]
'text': ugettext_lazy('Create User')}]
class ContextMixin(object):
@ -51,9 +51,9 @@ class UserCreate(ContextMixin, SuccessMessageMixin, CreateView):
form_class = CreateUserForm
template_name = 'users_create.html'
model = User
success_message = _('User %(username)s created.')
success_message = ugettext_lazy('User %(username)s created.')
success_url = reverse_lazy('users:create')
title = _('Create User')
title = ugettext_lazy('Create User')
def get_form_kwargs(self):
"""Make the request object available to the form."""
@ -66,7 +66,7 @@ class UserList(ContextMixin, ListView):
"""View to list users."""
model = User
template_name = 'users_list.html'
title = _('Users')
title = ugettext_lazy('Users')
class UserUpdate(ContextMixin, SuccessMessageMixin, UpdateView):
@ -75,8 +75,8 @@ class UserUpdate(ContextMixin, SuccessMessageMixin, UpdateView):
model = User
form_class = UserUpdateForm
slug_field = 'username'
success_message = _('User %(username)s updated.')
title = _('Edit User')
success_message = ugettext_lazy('User %(username)s updated.')
title = ugettext_lazy('Edit User')
def get_form_kwargs(self):
"""Make the requst object available to the form."""
@ -100,7 +100,7 @@ class UserDelete(ContextMixin, DeleteView):
model = User
slug_field = 'username'
success_url = reverse_lazy('users:index')
title = _('Delete User')
title = ugettext_lazy('Delete User')
def delete(self, *args, **kwargs):
"""Set the success message of deleting the user.
@ -110,7 +110,7 @@ class UserDelete(ContextMixin, DeleteView):
"""
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)
try:
@ -126,8 +126,8 @@ class UserChangePassword(ContextMixin, SuccessMessageMixin, FormView):
"""View to change user password."""
template_name = 'users_change_password.html'
form_class = UserChangePasswordForm
title = _('Change Password')
success_message = _('Password changed successfully.')
title = ugettext_lazy('Change Password')
success_message = ugettext_lazy('Password changed successfully.')
def get_form_kwargs(self):
"""Make the user object available to the form."""

View File

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

View File

@ -20,7 +20,7 @@ Forms for configuring XMPP service.
"""
from django import forms
from gettext import gettext as _
from django.utils.translation import ugettext_lazy as _
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.template.response import TemplateResponse
from gettext import gettext as _
from django.utils.translation import ugettext as _
import logging
import socket

View File

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

View File

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

View File

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