id(number) path in urls

Viewed 2473

I am new to django

In urls.py, I set path like this. I tried to create a page with urls: localhost:8000/topics/1/

urlpatterns = [
    path('topics/(?P<topic_id>\d+)/', views.topic, name='topic'),
]

In views.py. Code is this:

def topic(request, topic_id):
    """Show a single topic and all its entries"""
    topic = Topic.objects.get(id=topic_id)
    entries = topic.entry_set.order_by('date_added')
    context = {'topic': topic, "entries": entries}
    return render(request, 'learning_logs/topic.html', context)

I got error 404 when enter localhost:8000/topics/1/.

topics/(?P\d+)/ [name='topic']

The current path, topics/1/, didn't match any of these.

But the correct urls turns out to be: localhost:8000/topics/(%3FP1%5Cd+)/

Is there something wrong with the path in urls or what's the problem?

1 Answers

try this

urlpatterns = [
    path('topics/<topic_id>/', views.topic, name='topic'),
]

If you are expecting an integer, you could specify it as,

urlpatterns = [
    path('topics/<int:topic_id>/', views.topic, name='topic'),
]

Why topics/(?P<topic_id>\d+)/' not working?

Actulay you rae mixing the usage. If you are trying yo provide a regex included expression in your url, use re_path().
So, the pattern will be as,

from django.urls import re_path

urlpatterns = [
    re_path('topics/(?P<topic_id>\d+)/', views.topic, name='topic'),
]
Related