Home > Software design >  Django - Unable to pass page title as url parameter in template
Django - Unable to pass page title as url parameter in template

Time:05-25

I have a BIG problem. I need to pass article title to URL in the template

This is my 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})

At first I tried

<a href="{% url 'view' id=3685 title='What a terrible weather' %}">What a terrible weather</a>

And I got that error message:

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 )/$']
***

Then I tried

{% with thevarable= "What a terrible weather" %}     
    <a href="{% url 'view' id=3685 title=thevarable %}">What a terrible weather</a>
{% endwith %}

The result:

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
***

Also I tried

{% with my_var = 'What a terrible weather'.replace(' ','_') %}
    <div>Hello, {{my_var}}!</div>
{% endwith %}

As a result I go the same error:

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
***

Then I tried

{{ title|urlencode:"What a terrible weather" }}

Result: To my surprise it returned ID instead of Title

I tried that too. And It's the only possible way it works. It only works if we pass a single word as parameter BUT Who need it? It's a nonsense form.

<a href="{% url 'view' id=3685 title='idontneedtopassanparameterlikethat' %}">idontneedtopassanparameterlikethat</a>

As I can see on my clock, I waisted four hours to in searching a solution which I couldn't found And in conclution I think this maybe my last project on Django framework. Time is more expensive than money. I even spent a lot of time on the Django Framework and even got bored.

Please, help me to find a answer.

CodePudding user response:

Try using a string on path

path('view/<int:id>/<str:title>/', views.view, name='view'),

  • Related