Browse Source

Enable locale middleware and language selection by default

David Cramer 13 years ago
parent
commit
3b303699ba

+ 1 - 0
MANIFEST.in

@@ -1,5 +1,6 @@
 include setup.py README.rst MANIFEST.in LICENSE AUTHORS
 recursive-include sentry/templates *
+recursive-include sentry/locale *
 recursive-include sentry/static *
 recursive-include sentry/plugins/*/templates *
 global-exclude *~

+ 2 - 0
sentry/conf/defaults.py

@@ -14,6 +14,8 @@ import os.path
 
 ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir))
 
+MODULE_ROOT = os.path.dirname(__import__('sentry').__file__)
+
 # Allow local testing of Sentry even if DEBUG is enabled
 DEBUG = False
 

+ 1 - 0
sentry/conf/server.py

@@ -80,6 +80,7 @@ TEMPLATE_LOADERS = (
 MIDDLEWARE_CLASSES = (
     'django.middleware.common.CommonMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.middleware.locale.LocaleMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'sentry.middleware.SentryMiddleware',

+ 13 - 0
sentry/conf/settings.py

@@ -37,6 +37,19 @@ if locals().get('DEFAULT_PROJECT_ACCESS') not in ('MEMBER_OWNER', 'MEMBER_USER',
     DEFAULT_PROJECT_ACCESS = 'MEMBER_OWNER'
 
 
+def get_all_languages():
+    results = []
+    for path in os.listdir(os.path.join(MODULE_ROOT, 'locale')):
+        if path.startswith('.'):
+            continue
+        results.append(path)
+    return results
+
+# Setup languages for only available locales
+LANGUAGE_MAP = dict(settings.LANGUAGES)
+LANGUAGES = ((k, LANGUAGE_MAP[k]) for k in get_all_languages() if k in LANGUAGE_MAP)
+
+
 def configure(**kwargs):
     for k, v in kwargs.iteritems():
         if k.upper() != k:

+ 1 - 0
sentry/conf/urls.py

@@ -39,6 +39,7 @@ def handler500(request):
     return HttpResponseServerError(t.render(Context(context)))
 
 urlpatterns += patterns('',
+    (r'^i18n/', include('django.conf.urls.i18n')),
     (r'^admin/', include(admin.site.urls)),
     url(r'^_admin_media/(?P<path>.*)$', generic.static_media,
         kwargs={'root': admin_media_dir},

+ 6 - 2
sentry/templates/sentry/account/settings.html

@@ -31,7 +31,7 @@
                     </ul>
                 </div>
             {% endif %}
-            <p>To make changes to your account, you must first enter your current password.</p>
+            <p>{% trans "To make changes to your account, you must first enter your current password." %}</p>
             {% with form.old_password as field %}
                 {% include "sentry/partial/_form_field.html" %}
             {% endwith %}
@@ -42,14 +42,18 @@
             {% with form.email as field %}
                 {% include "sentry/partial/_form_field.html" %}
             {% endwith %}
+            {% with form.language as field %}
+                {% include "sentry/partial/_form_field.html" %}
+            {% endwith %}
             <hr>
-            <p>You may also optionally change your password.</p>
+            <p>{% trans "You may also optionally change your password." %}</p>
             {% with form.new_password1 as field %}
                 {% include "sentry/partial/_form_field.html" %}
             {% endwith %}
             {% with form.new_password2 as field %}
                 {% include "sentry/partial/_form_field.html" %}
             {% endwith %}
+
             <fieldset class="form-actions">
                 <button type="submit" class="btn btn-primary">{% trans "Save Changes" %}</button>
             </fieldset>

+ 13 - 11
sentry/web/forms.py

@@ -11,6 +11,7 @@ from django.utils.encoding import force_unicode
 from django.utils.safestring import mark_safe
 from django.utils.translation import ugettext_lazy as _
 
+from sentry.conf import settings
 from sentry.models import Project, ProjectMember
 from sentry.interfaces import Http
 
@@ -44,14 +45,14 @@ class UserField(forms.CharField):
         try:
             return User.objects.get(username=value)
         except User.DoesNotExist:
-            raise forms.ValidationError(u'invalid user name')
+            raise forms.ValidationError(_('Invalid username'))
 
 
 class RemoveProjectForm(forms.Form):
     removal_type = forms.ChoiceField(choices=(
-        ('1', 'Remove all attached events.'),
-        ('2', 'Migrate events to another project.'),
-        ('3', 'Hide this project.'),
+        ('1', _('Remove all attached events.')),
+        ('2', _('Migrate events to another project.')),
+        ('3', _('Hide this project.')),
     ), widget=forms.RadioSelect(renderer=RadioFieldRenderer))
     project = forms.ChoiceField(choices=(), required=False)
 
@@ -67,7 +68,7 @@ class RemoveProjectForm(forms.Form):
     def clean(self):
         data = self.cleaned_data
         if data.get('removal_type') == 2 and not data.get('project'):
-            raise forms.ValidationError('You must select a project to migrate data')
+            raise forms.ValidationError(_('You must select a project to migrate data'))
         return data
 
     def clean_project(self):
@@ -121,7 +122,7 @@ class NewProjectMemberForm(BaseProjectMemberForm):
             return None
 
         if self.project.member_set.filter(user=value).exists():
-            raise forms.ValidationError('User already a member of project')
+            raise forms.ValidationError(_('User already a member of project'))
 
         return value
 
@@ -142,14 +143,14 @@ class ReplayForm(forms.Form):
 
 class BaseUserForm(forms.ModelForm):
     email = forms.EmailField()
-    first_name = forms.CharField(required=True, label='Name')
+    first_name = forms.CharField(required=True, label=_('Name'))
 
 
 class NewUserForm(BaseUserForm):
     create_project = forms.BooleanField(required=False,
-        help_text="Create a project for this user.")
+        help_text=_("Create a project for this user."))
     send_welcome_mail = forms.BooleanField(required=False,
-        help_text="Send this user a welcome email which will contain their generated password.")
+        help_text=_("Send this user a welcome email which will contain their generated password."))
 
     class Meta:
         fields = ('first_name', 'username', 'email')
@@ -164,8 +165,8 @@ class ChangeUserForm(BaseUserForm):
 
 class RemoveUserForm(forms.Form):
     removal_type = forms.ChoiceField(choices=(
-        ('1', 'Disable the account.'),
-        ('2', 'Permanently remove the user and their data.'),
+        ('1', _('Disable the account.')),
+        ('2', _('Permanently remove the user and their data.')),
     ), widget=forms.RadioSelect(renderer=RadioFieldRenderer))
 
 
@@ -175,6 +176,7 @@ class AccountSettingsForm(forms.Form):
     first_name = forms.CharField(required=True, label='Name')
     new_password1 = forms.CharField(label=_("New password"), widget=forms.PasswordInput, required=False)
     new_password2 = forms.CharField(label=_("New password confirmation"), widget=forms.PasswordInput, required=False)
+    language = forms.ChoiceField(label=_('Language'), choices=settings.LANGUAGES)
 
     def __init__(self, user, *args, **kwargs):
         self.user = user

+ 8 - 1
sentry/web/frontend/accounts.py

@@ -5,6 +5,7 @@ sentry.web.frontend.accounts
 :copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
 :license: BSD, see LICENSE for more details.
 """
+from django.conf import settings as dj_settings
 from django.core.context_processors import csrf
 from django.core.urlresolvers import reverse
 from django.http import HttpResponseRedirect
@@ -48,10 +49,16 @@ def settings(request):
     form = AccountSettingsForm(request.user, request.POST or None, initial={
         'email': request.user.email,
         'first_name': request.user.first_name,
+        'language': request.LANGUAGE_CODE,
     })
     if form.is_valid():
         form.save()
-        return HttpResponseRedirect(reverse('sentry-account-settings') + '?success=1')
+        response = HttpResponseRedirect(reverse('sentry-account-settings') + '?success=1')
+        if hasattr(request, 'session'):
+            request.session['django_language'] = form.cleaned_data['language']
+        else:
+            response.set_cookie(dj_settings.LANGUAGE_COOKIE_NAME, form.cleaned_data['language'])
+        return response
 
     context = csrf(request)
     context.update({