Skip to content

Commit

Permalink
Merge pull request #564 from Ilhasoft/feature/add_middleware_to_chang…
Browse files Browse the repository at this point in the history
…e_language

Feature/add middleware to change language
  • Loading branch information
dyohan9 committed Apr 1, 2021
2 parents 25e653f + b967ac0 commit 8c68bff
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 1 deletion.
2 changes: 1 addition & 1 deletion bothub/api/v2/account/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class RegisterUserSerializer(serializers.ModelSerializer):

class Meta:
model = User
fields = ["email", "name", "nickname", "password"]
fields = ["email", "name", "nickname", "password", "language"]
ref_name = None

@staticmethod
Expand Down
18 changes: 18 additions & 0 deletions bothub/api/v2/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from django.utils import translation
from django.utils.deprecation import MiddlewareMixin


class UserLanguageMiddleware(MiddlewareMixin):
def process_response(self, request, response):
user = getattr(request, "user", None)
if not user or user.is_anonymous:
return self.get_response(request)

user_language = getattr(user, "language", None)
if not user_language:
return self.get_response(request)

translation.activate(user_language)

response = self.get_response(request)
return response
21 changes: 21 additions & 0 deletions bothub/authentication/migrations/0008_user_language.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Generated by Django 2.2.19 on 2021-03-31 14:14

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [("authentication", "0007_auto_20210323_0035")]

operations = [
migrations.AddField(
model_name="user",
name="language",
field=models.CharField(
blank=True,
choices=[("en", "English"), ("pt-br", "Brazilian Portuguese")],
max_length=5,
null=True,
),
)
]
3 changes: 3 additions & 0 deletions bothub/authentication/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ class Meta:
parent_link=True,
related_name="user_owner",
)
language = models.CharField(
max_length=5, choices=settings.LANGUAGES, null=True, blank=True
)

objects = UserManager()

Expand Down
1 change: 1 addition & 0 deletions bothub/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"bothub.api.v2.middleware.UserLanguageMiddleware",
]

ROOT_URLCONF = "bothub.urls"
Expand Down

0 comments on commit 8c68bff

Please sign in to comment.