Django:仅在本地翻译的身份验证表?

时间:2019-03-18 21:53:13

标签: django

我正在使用Django的默认Authentication表单。

这是Django默认的AuthenticationForm实现:

from django.contrib.auth.forms import AuthenticationForm 

我已经将默认的error_messages转换为西班牙语:

error_messages = {
            'invalid_login': _(
                "- Por favor, ingrese un nombre de usuario y contraseña correctos. "
                "- Diferencie entre minúsculas y mayúsculas."
            ),

但是,当将应用程序上载到生产环境(Heroku)时,这些更改是不可见的(似乎仅在本地应用)。

为什么?

class AuthenticationForm(forms.Form):
    """
    Base class for authenticating users. Extend this to get a form that accepts
    username/password logins.
    """
    username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True}), label="Usuario")
    password = forms.CharField(
        label=_("Contraseña"),
        strip=False,
        widget=forms.PasswordInput,
    )

    error_messages = {
        'invalid_login': _(
            "- Por favor, ingrese un nombre de usuario y contraseña correctos. "
            "- Diferencie entre minúsculas y mayúsculas."
        ),
        'inactive': _("Esta cuenta no está activa."),
    }

    def __init__(self, request=None, *args, **kwargs):
        """
        The 'request' parameter is set for custom auth use by subclasses.
        The form data comes in via the standard 'data' kwarg.
        """
        self.request = request
        self.user_cache = None
        super().__init__(*args, **kwargs)

        # Set the max length and label for the "username" field.
        self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
        self.fields['username'].max_length = self.username_field.max_length or 254
        if self.fields['username'].label is None:
            self.fields['username'].label = capfirst(self.username_field.verbose_name)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username is not None and password:
            self.user_cache = authenticate(self.request, username=username, password=password)
            if self.user_cache is None:
                raise self.get_invalid_login_error()
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data

    def confirm_login_allowed(self, user):
        """
        Controls whether the given User may log in. This is a policy setting,
        independent of end-user authentication. This default behavior is to
        allow login by active users, and reject login by inactive users.

        If the given user cannot log in, this method should raise a
        ``forms.ValidationError``.

        If the given user may log in, this method should return None.
        """
        if not user.is_active:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )

    def get_user(self):
        return self.user_cache

    def get_invalid_login_error(self):
        return forms.ValidationError(
            self.error_messages['invalid_login'],
            code='invalid_login',
            params={'username': self.username_field.verbose_name},
        )

1 个答案:

答案 0 :(得分:1)

原因是因为当您推送到Heroku时,它不会推送您在默认实现中所做的更改。相反,它将安装您的requirements.txt中指定的Django的默认版本。因此,您可以做的是创建一个自定义认证表单,该表单继承自Django的默认实现,进行所需的更改,然后在您的url中指定此自定义表单:

# forms.py
from django.contrib.auth.forms import AuthenticationForm

class CustomAuthenticationForm(AuthenticationForm):
    username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True}), label="Usuario")
    password = forms.CharField(
        label=_("Contraseña"),
        strip=False,
        widget=forms.PasswordInput,
    )

    error_messages = {
        'invalid_login': _(
            "- Por favor, ingrese un nombre de usuario y contraseña correctos. "
            "- Diferencie entre minúsculas y mayúsculas."
        ),
        'inactive': _("Esta cuenta no está activa."),
    }

    def __init__(self, request=None, *args, **kwargs):
        self.request = request
        self.user_cache = None
        super().__init__(*args, **kwargs)

        # Set the max length and label for the "username" field.
        self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
        self.fields['username'].max_length = self.username_field.max_length or 254
        if self.fields['username'].label is None:
            self.fields['username'].label = capfirst(self.username_field.verbose_name)


# urls.py
from .forms import CustomAuthenticationForm

url(r'^login/$', auth_views.LoginView.as_view(template_name='registration/login.html', authentication_form= CustomAuthenticationForm), name='login'),