问题
I have added search
url to i18n_patterns
, but the language switcher doesn't work on that page.
urls.py:
urlpatterns += i18n_patterns(
path("search/", search_views.search, name="search"),
path("", include(wagtail_urls)),
)
language switcher:
{% get_available_languages_wmt as languages %}
<div class="nav-item dropdown float-right">
<p class="nav-link dropdown-toggle m-auto" data-toggle="dropdown" role="button" aria-expanded="false">
{{ request.LANGUAGE_CODE|upper }}</p>
<div class="dropdown-menu w-25">
{% for language in languages %}
{% if language != request.LANGUAGE_CODE %}
<a class="dropdown-item" href="{% change_lang language page %}">{{ language|upper }}</a>
{% endif %}
{% endfor %}
</div>
</div>
Furthermore, when i add search
url above root
one the search page raises 404 page.
How can i make the language switcher work on the search page?
回答1:
The language switcher uses the Wagtail page
variable. See the change_lang
template tag:
<a ... href="{% change_lang language page %}">...</a>
And search is a Django view, not a Wagtail page. The page
variable is not defined.
You can make the switcher work on the search view by setting the href yourself:
{% for language in languages %}
<a href="/{{ language.code }}/search/"
{% endfor %}
Alternatively, you can create a Wagtail search page:
class SearchPage(Page):
def get_context(self, request):
context = super().get_context(request)
... # Copy the code from the current search view.
# Update and return the context
context.update({
'search_query': search_query,
'search_results': search_results,
})
return context
https://docs.wagtail.io/en/latest/topics/pages.html#customising-template-context
You also have to:
- Rename (search_page.html) and rework (page.variable_name) your search template.
- Remove the search url from urls.py
- Add the SearchPage via the Wagtail admin interface to the page tree.
来源:https://stackoverflow.com/questions/64193166/wagtail-modeltranslation-language-switcher-doesnt-work-on-search-page