V
V
Vladislav Sklyar2015-07-29 14:13:16
Django
Vladislav Sklyar, 2015-07-29 14:13:16

Displaying translated message using jquery?

Hello. Created an invitation form to the site with one email field. With the help of ajax I send data, in the view I do checks. Elsi everything is OK I send a letter and a reply with a message, if not just a message. I want to add translation of messages, but when I did everything, the message is not translated. Help plz.
view.py

from django.utils.translation import ugettext_lazy as _

def invite(request):
    if request.method == 'POST':
        email = request.POST['email']
        msg = ''
        response_data = {}
        if User.objects.filter(email=email).exists():
            msg = _("User with this email are register")
        elif UserInvite.objects.filter(email=email).exists():
            msg = _("In this email Invite already sent")
        else:
            UserInvite.objects.create(
                user=request.user,
                email=email
                )
            send_mail('Hi! This your invite.',
                      'Hi! You can register in our web-site.' + '\n' +
                      request.build_absolute_uri(reverse('register')),
                      '[email protected]', [email],
                      fail_silently=False)
            msg = _("Thank you for invite your friends!!!")
            response_data['msg'] = unicode(msg)
    return JsonResponse(response_data)

ajax:
$.ajax({
            method: "POST",
            url: '/invite/',
            data: {
            'email': email.val(),
            'csrfmiddlewaretoken': CSRF_TOKEN
            },
            success: function(response, status) {
              updateTips(response['msg'])
                },
            error: function(response) {
              updateTips("Error")
            }
          });

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladislav Sklyar, 2015-11-23
@VladSkliar

The solution is simple: add the localization code to the request data, and select it in the view. Django automatically sets the English language in the response to the request
In the script:

var lang = $('html').attr('lang');

$.ajax({
            method: "POST",
            url: '/invite/',
            data: {
            'csrfmiddlewaretoken': CSRF_TOKEN,
            'language':lang
            },

In the view:
translation.activate(request.POST['language'])

O
Oscar Django, 2015-07-29
@winordie

Did you give it all?
djbook.ru/rel1.8/topics/i18n/translation.html#how-...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question