Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include in django template a reverse url in translation

Tags:

python

django

I have the following block of code, And I want to include a url to the login page, after the user logs out, in a translatable text.

Unfortunately, translation blocks cannot include tags, and I get the following error:

SyntaxError: Translation blocks must not include other block tags: url "account:login"

{% blocktrans %}


You have been successfully logged out.


You can <a href="{% url "account:login" %}">log-in again</a>.


{% endblocktrans %}

urls.py:

from django.urls import path

from django.contrib.auth import views as auth_views



app_name = 'account'



urlpatterns = [

    path('login/', auth_views.LoginView.as_view(), name='login'),

    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]

What would be the right way to achieve something like this?

Edit: I figured there are workarounds, such as translating blocks of text separately, or using javascript to append the "href" element after the page loads. But I wonder if there is a more efficient, Django way.

like image 723
Petru Tanas Avatar asked Oct 31 '25 06:10

Petru Tanas


1 Answers

As documented

Reverse URL lookups cannot be carried out within the blocktrans and should be retrieved (and stored) beforehand:

{% url 'path.to.view' arg arg2 as the_url %}
{% blocktrans %}
This is a URL: {{ the_url }}
{% endblocktrans %}
like image 100
iklinac Avatar answered Nov 02 '25 20:11

iklinac