Django - Невозможно передать заголовок страницы в качестве url-параметра в шаблоне
У меня большая проблема. Мне нужно передать заголовок статьи в URL в шаблоне
Это мой urls.py
urlpatterns = [
***
re_path(r'^view/(?P<id>\w+)/(?P<title>\w+)/$', views.view, name='view'),
***
]
view.py
def view(request, id, title):
return render(request, 'view.html', {'id' : id, 'title' : title})
Сначала я пытался
<a href="{% url 'view' id=3685 title='What a terrible weather' %}">What a terrible weather</a>
И я получил сообщение об ошибке:
NoReverseMatch at /view/7/6999/
Reverse for 'view' with keyword arguments '{'id': 3685, 'title': 'What a terrible weather'}' not found. 1 pattern(s) tried: ['view/(?P<id>\\w+)/(?P<title>\\w+)/$']
***
Error during template rendering
In template D:\Django\gtunews\templates\view.html, error at line 8 Reverse for 'view' with keyword arguments '{'id': 3685, 'title': 'What a terrible weather'}' not found.
1 pattern(s) tried: ['view/(?P<id>\\w+)/(?P<title>\\w+)/$']
***
Тогда я попытался
{% with thevarable= "What a terrible weather" %}
<a href="{% url 'view' id=3685 title=thevarable %}">What a terrible weather</a>
{% endwith %}
Результат:
TemplateSyntaxError at /view/7/6999/
'with' expected at least one variable assignment
***
Error during template rendering
In template D:\Django\gtunews\templates\view.html, error at line 8
'with' expected at least one variable assignment
***
Также я попробовал
{% with my_var = 'What a terrible weather'.replace(' ','_') %}
<div>Hello, {{my_var}}!</div>
{% endwith %}
В результате я получаю ту же ошибку:
TemplateSyntaxError at /view/7/6999/
'with' expected at least one variable assignment
***
Error during template rendering
In template D:\Django\gtunews\templates\view.html, error at line 8
'with' expected at least one variable assignment
***
Тогда я попытался
{{ title|urlencode:"What a terrible weather" }}
Result: К моему удивлению, он вернул ID вместо Title
Я тоже так пробовал. И это единственный возможный способ, который работает. Он работает только если мы передаем одно слово в качестве параметра BUT Кому это нужно? Это бессмысленная форма
<a href="{% url 'view' id=3685 title='idontneedtopassanparameterlikethat' %}">idontneedtopassanparameterlikethat</a>
Как я вижу на своих часах, я потратил четыре часа на поиск решения, которое так и не нашел. И в заключение я думаю, что это, возможно, мой последний проект на фреймворке Django. Время дороже денег. Я потратил много времени на Django Framework и даже успел заскучать.
Пожалуйста, помогите мне найти ответ.
Попробуйте использовать строку на пути
path('view/<int:id>/<str:title>/', views.view, name='view'),