You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django 2.0 路由配置报错求助:正则表达式组名格式错误

Fixing Django 2.0 URL Routing Issues with path/re_path

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+), but int:id isn't a valid group name—it includes a colon, which is illegal here. That's exactly why you're getting the ImproperlyConfigured exception about invalid characters in the group name.
  • Your commented path line 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.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:50:33