如何覆盖默认的error_messages?例如required或invalid_login?我使用的是版本1.9.2。
from django.conf.urls import url, include
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import user_passes_test
from django.conf import settings
anonymous_required = user_passes_test(
lambda user: user.is_anonymous(),
settings.LOGIN_REDIRECT_URL,
redirect_field_name = 'next')
urlpatterns = [
url(r'^products/', include('products.urls', namespace = 'products')),
url(r'^orders/', include('orders.urls', namespace = 'orders')),
url(r'^calendar/', include('installation_dates.urls', namespace = 'installation_dates')),
url(r'^supplies/', include('supplies.urls', namespace = 'supplies')),
url(r'^manufacturer/', include('manufacturer.urls', namespace = 'manufacturer')),
url(r'^users/', include('users.urls', namespace = 'users')),
url(r'^login/$', anonymous_required(auth_views.login), name = 'login'),
url(r'^logout/$', auth_views.logout, {'next_page': '/login/'}, name = 'logout'),
]
[解决方案]在我看来,这是最好的解决方案:
forms.py:
的一部分from django.contrib.auth.forms import AuthenticationForm
class UserLoginForm(AuthenticationForm):
error_messages = {
'invalid_login': 'Podane dane logowania są niepoprawne.',
'required_password': 'Wymagane jest podanie hasła.',
'required_username': 'Wymagane jest podanie nazwy użytkownika.',
}
username = forms.CharField(
error_messages = {
'required': error_messages.get('required_username'),
},
)
password = forms.CharField(
error_messages = {
'required': error_messages.get('required_password'),
},
)
和urls.py:
# -*- coding: utf-8 -*-
from django.conf.urls import url, include
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import user_passes_test
from django.conf import settings
from users.forms import UserLoginForm
anonymous_required = user_passes_test(
lambda user: user.is_anonymous(),
settings.LOGIN_REDIRECT_URL,
redirect_field_name = 'next')
urlpatterns = [
url(r'^products/', include('products.urls', namespace = 'products')),
url(r'^orders/', include('orders.urls', namespace = 'orders')),
url(r'^calendar/', include('installation_dates.urls', namespace = 'installation_dates')),
url(r'^supplies/', include('supplies.urls', namespace = 'supplies')),
url(r'^manufacturer/', include('manufacturer.urls', namespace = 'manufacturer')),
url(r'^users/', include('users.urls', namespace = 'users')),
url(r'^login/$', anonymous_required(auth_views.login), {'authentication_form': UserLoginForm}, name = 'login'),
url(r'^logout/$', auth_views.logout, {'next_page': '/login/'}, name = 'logout'),
]
感谢您的帮助。