Django 2.0 路由配置报错求助:正则表达式组名格式错误
Got it, let's sort out this URL routing problem you're facing with Django 2.0. The errors you're seeing come from mixing up the syntax rules for path and re_path (the alias for the old url function).
What's Causing the Errors?
- For
re_path(regex-based routing), named capture groups follow standard regex format:(?P<name>pattern). You tried using(?P<int:id>\d+), butint:idisn't a valid group name—it includes a colon, which is illegal here. That's exactly why you're getting theImproperlyConfiguredexception about invalid characters in the group name. - Your commented
pathline is actually correct syntax! The reason you saw<int:id>in the browser address bar is likely because you hadn't uncommented that line yet, so Django wasn't parsing the path converter.
Solution 1: Use path (Recommended for Django 2.0+)
This is the cleanest approach since Django 2.0 introduced path converters. Just uncomment your existing path line (and optionally add a name for reverse routing):
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), # Uncomment this line and remove the faulty re_path path('details/<int:id>/', views.details, name='todo_details'), ]
The <int:id> converter will automatically match numeric values, cast id to an integer, and pass it directly to your details view—perfect for your existing view function that expects an integer id parameter.
Solution 2: Use re_path (If You Need Regex Routing)
If you prefer to stick with regex-based routing, fix the named capture group by removing the int: prefix. You'll also want to ensure the id parameter is cast to an integer in your view (the ORM can handle string IDs, but explicit casting is safer):
Updated urls.py:
from django.urls import path, re_path from . import views urlpatterns = [ path('', views.index, name='index'), # Fixed regex group name (removed int:) re_path(r'^details/(?P<id>\d+)/$', views.details, name='todo_details'), ]
Updated views.py (optional but recommended):
def details(request, id): # Cast id to integer explicitly todo = Todo.objects.get(id=int(id)) context = { 'todo': todo } return render(request, 'details.html', context)
Testing the Fix
Once you apply either solution, restart your Django development server. Visit a URL like http://127.0.0.1:8000/todo/details/1/ (replace 1 with a valid Todo ID in your database) — it should load the details page without errors, and the address bar will show the numeric ID instead of <int:id>.
内容的提问来源于stack exchange,提问作者meme

