from django.conf.urls import url
from django.urls import path, re_path
from . import views
urlpatterns = [
path('', views.index, name='index'),
#path('details/<int:id>/', views.details),
#re_path(r'^details/(?P<int:id>\d+)/$', views.details),
]
Kindly assist me with the commented URLs patterns above. I am using Django 2.0. When I run the browser I get
django.core.exceptions.ImproperlyConfigured: "^details/(?P<int:id>\d+)/$" is not a valid regular expression: bad character in group name 'int:id' at position 13
My views.py is as below:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Todo # to render todo items
def index(request):
todos = Todo.objects.all() [:10] # define we want 10
context = {
'todos':todos # pass it onto a template variable todos
}
return render(request, 'index.html', context)
def details(request, id):
todo=Todo.objects.get(id=id)
context = {
'todo':todo # pass it onto a template variable todos
}
return render(request, 'details.html', context)
and the web address displayed by the browser is:
http://127.0.0.1:8000/todo/details/<int:id>/
Your URL pattern using path()
looks OK.
path('details/<int:id>/', views.details),
The re_path
is incorrect, because <int:id>
is not a valid. Remove the int:
.
re_path(r'^details/(?P<id>\d+)/$', views.details),
You only need to enable one of these, since they both match the same URLs, e.g. /details/5/
.
As an aside, you may want to use get_object_or_404()
instead of Todo.objects.get()`. This will handle the case when a todo with that id does not exist.
from django.shortcuts import get_object_or_404
todo = get_object_or_404(Todo, id=id)