Как отображать переводы в каждом тексте справки по проверке пароля в Django? - PullRequest
0 голосов
/ 09 июля 2020

Несмотря на то, что тексты справки по проверке пароля переведены на официальный греческий перевод ( здесь ), похоже, они не отображаются в моем приложении 3.0.3. Вот скриншот пользовательской формы регистрации.

enter image description here

As you can see the only working translation appears to be the one corresponding to MinimumLengthValidator while the others appear in English, despite the browser's Greek language setting. I would like to know a way to introduce translations for the entirety of help_text bullets under the password field in the registration form.

Some crucial parts of my code

settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {
            'min_length': 8,
        }
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'el'

LANGUAGES = [
    ('el', _('Greek')),
    ('en', _('English')),
]

LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

TIME_ZONE = 'Europe/Athens'

USE_I18N = True

USE_L10N = False

USE_TZ = True

forms.py

from django import forms
from django.contrib.auth import authenticate, login, get_user_model
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, ReadOnlyPasswordHashField
from django.urls import reverse
from django.utils.html import mark_safe
from django.utils.translation import ugettext as _

User = get_user_model()

from .models import User, Profile, EmailActivation

class RegisterForm(UserCreationForm):
    email = forms.EmailField(
        label='E-mail',
        help_text=_('Please add a valid e-mail address.'),
    )
    accept_tou = forms.BooleanField(
        required=False,
        label=_('I have read and accept the Terms of Use.'),
    )

    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if field_name != 'accept_tou':
                if field.widget.attrs.get('class'):
                    field.widget.attrs['class'] += ' form-control'
                else:
                    field.widget.attrs['class'] = 'form-control'

    def clean_accept_tou(self):
        accepted_tou = self.cleaned_data.get('accept_tou')
        if not accepted_tou:
            raise forms.ValidationError("You cannot register unless \
                you accept our Terms of Use")

    class Meta:
        model = User
        fields = ('email', 'password1', 'password2')

views.py

from django.views.generic.edit import CreateView
from .forms import RegisterForm

class RegisterView(CreateView):
    form_class = RegisterForm
    template_name = 'accounts/register.html'
    success_url = reverse_lazy("accounts:email-register")

    def get_context_data(self, *args, **kwargs):
        context = super(RegisterView, self).get_context_data(*args, **kwargs)
        context["title"] = _("Register")
        context["header"] = _("Register")
        return context

register.html

{% extends "base.html" %}

{% load i18n %}

{% block title %}{{ title }}{% endblock %}

{% block content %}

     {% if header%} {{header}}  {% endif%}  {% csrf_token%} {% для поля в форме%} {% if field.name == 'accept_tou'%} {{field}} {% trans 'Я прочитал и принимаю'%}  {% trans 'Условия использования для зарегистрированных пользователей'%} . {% else%} {{field.label_tag}} {{field}} {% endif%} {% if field.help_text%} {{field.help_text}}  {% endif%} {% if field. ошибки%} {% для ошибки в field.errors%} {{error}}  {% endfor%}  {% endif%}  {% endfor%} {% trans 'Register'%}     {% endblock%} 
...