How do you translate the slug value of a page?

北慕城南 提交于 2021-02-10 23:30:22

问题


I'm trying to implement a language switcher, for which I'm using the Django recommended form:

    <form action="{% url 'set_language' %}" method="post">{% csrf_token %}
        {% get_current_language as LANGUAGE_CODE %}
        <input name="next" type="hidden" value="{{ redirect_to }}">
        <input name="language" type="hidden" value="{% if LANGUAGE_CODE == 'en' %}es{% else %}en{% endif %}">
    </form>

My urls.py is set up like so:

urlpatterns = [

    # Wagtail urls
    re_path(r'^cms/', include(wagtailadmin_urls)),
    re_path(r'^documents/', include(wagtaildocs_urls)),

    # Django urls
    path('admin/', admin.site.urls),
    path('i18n/', include('django.conf.urls.i18n')),

]

urlpatterns += i18n_patterns(
    path(r'', include(wagtail_urls))
)

When I click to change my language, I am correctly forwarded to /en/slug or es/slug, depending on the language I have selected. However the actual slug value is not being translated. Since I have Spanish slugs for the Spanish pages, I am getting a 404 when I switch languages, because I am directed to the English slug value paired with the Spanish locale prefix (es).

I also tried using the slugurl_trans template tag, but that didn't seem to work (maybe because I'm not explicitly defining any URLs in my i18n_patterns call?).

Any guidance on this would be really helpful, as I've spent way too many hours on this!


回答1:


It has been long but I'm going to post an answer anyway, the best way to get rid of the different slugs problem is by using django signals like this

@receiver(pre_save)
def set_translated_slug_on_new_instance(sender, instance, **kwargs):
    if isinstance(instance, Page):
        instance.slug_es = instance.slug_en


来源:https://stackoverflow.com/questions/57698884/how-do-you-translate-the-slug-value-of-a-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!