这是我的语言转换表格。
{% get_current_language as lang_code %}
{% get_available_languages as languages %}
{% get_language_info_list for languages as langs %}
<form action="{% url 'set_language' %}" method="POST">
{% csrf_token %}
<select name="language" title="{% translate 'Language' %}">
{% for lang in langs %}
<option value="{{ lang.code }}"{% if lang.code == lang_code %} selected{% endif %}>
{{ lang.name_local }} ({{ lang.name_translated }})
</option>
{% endfor %}
</select>
<input type="submit" value="OK" />
</form>
我把它包含在基础模板的页脚。
然后,这是我的courses/urls.py (app urls)。
from django.contrib import admin
from django.urls import path
from django.utils.translation import gettext_lazy as _
from . import views
admin.site.site_header = _("FilFak administration")
admin.site.site_title = _("FilFak admin")
admin.site.index_title = _("Manage FilFak")
urlpatterns=[
path("courses/", views.CourseList.as_view(), name="course_list"),
path("professors/", views.ProfessorList.as_view(), name="professor_list"),
path("exams/", views.ExamList.as_view(), name="exam_list"),
path("courses/<slug:slug>", views.CourseDetails.as_view(), name="course_details"),
path("professors/<slug:slug>", views.ProfessorDetails.as_view(), name="professor_details"),
path("exams/<slug:slug>", views.ExamDetails.as_view(), name="exam_details"),
path("", views.Index.as_view(), name="index"),
]
filfak/urls.py (project urls.py)
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.i18n import i18n_patterns
from django.conf.urls.static import static
from django.conf import settings
from django.utils.translation import gettext_lazy as _
urlpatterns = [
path("admin/", admin.site.urls),
path("lang/", include("django.conf.urls.i18n")),
]
urlpatterns += i18n_patterns(
path("", include("courses.urls")),
prefix_default_language=False
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
下面是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",
]
当我在语言切换表单上单击OK时,它实际上只在默认语言的主页上更改语言。对于任何其他URL,它只是刷新页面,而不更改语言。
我做错了什么吗?
检查USE_I18N
的标志值,看起来它被设置为False
,这就是为什么语言没有正确设置的原因。
改为:-
USE_I18N = True
根据Django文档:-
如果不使用国际化,则应该花两秒钟的时间在设置文件中设置USE_I18N = False。