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

时间:2018-01-16 13:04:10

标签: python django url-pattern

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

]

请帮我处理上面评论的网址格式。我正在使用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>/

1 个答案:

答案 0 :(得分:0)

使用path()的网址格式看起来不错。

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

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

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

您只需要启用其中一个,因为它们都匹配相同的网址,例如/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)