不是有效的正则表达式:组名中的错误字符 'int:id' 在位置 13

is not a valid regular expression: bad character in group name 'int:id' at position 13

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),

]

请协助我处理上面的评论 URL 模式。我正在使用 Django 2.0。当我 运行 浏览器时,我得到

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

我的views.py如下:

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)

浏览器显示的网址为:

http://127.0.0.1:8000/todo/details/<int:id>/

您使用 path() 的 URL 模式看起来不错。

path('details/<int:id>/', views.details),

re_path不正确,因为<int:id>无效。删除 int:.

 re_path(r'^details/(?P<id>\d+)/$', views.details),

您只需启用其中一项,因为它们都匹配相同的 URL,例如/details/5/.

顺便说一句,您可能想使用 get_object_or_404() 而不是 Todo.objects.get()`。这将处理不存在具有该 ID 的待办事项的情况。

from django.shortcuts import get_object_or_404

todo = get_object_or_404(Todo, id=id)