0Pricing
Django Academy · 课时

捕获 URL 参数

在视图中读取 int、slug 等路径转换器

捕获 URL 参数 是 CoddyKit 上的免费 Django Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Django Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Django Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Capture Parameters

Many pages depend on a value in the URL, like a product id. Django lets you capture that value and pass it straight to your view.

Angle Bracket Syntax

You capture a piece of the URL with angle brackets. Whatever is inside becomes a named argument for your view.

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

Converters Set the Type

The word before the colon is a converter. It both matches a pattern and converts the captured text to the right Python type.

The int Converter

The int converter matches digits and hands your view a real integer, not a string. Perfect for numeric ids.

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

The slug Converter

The slug converter matches letters, numbers, hyphens, and underscores. It is ideal for readable, SEO-friendly URLs.

path('blog/<slug:title>/', views.post)

The View Receives the Value

The captured name becomes a parameter in your view, right after request. The names must match exactly.

def detail(request, id):
    return HttpResponse('Post ' + str(id))

Names Must Match

The name in the URL and the view argument must be identical. If the URL says id, your view must accept id too.

More Built-in Converters

Beyond int and slug, Django ships str, uuid, and path converters. Each matches a different shape of value.

str Is the Default

If you skip the converter, Django uses str. It matches any text except a slash, which keeps segments separate.

path('user/<username>/', views.profile)

Capturing Multiple Values

You can capture several values in one route. Each becomes its own keyword argument in the view, in order.

path('<int:year>/<int:month>/', views.archive)

Wrong Type, No Match

If a URL value does not fit the converter, the route simply does not match. Django moves on or returns a 404.

Quick Check

Consider which converter fits a numeric id.

Recap: Dynamic URLs

Use angle brackets with a converter to capture URL values. The view receives them by name, typed and ready to use. ✨

常见问题解答

「捕获 URL 参数」课时是免费的吗?

是的 — 「捕获 URL 参数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Django Academy 课程的其余内容,请升级到 CoddyKit PRO。 Django Academy 课程共包含 4 节课。

「捕获 URL 参数」这节课中我会学到什么?

在视图中读取 int、slug 等路径转换器 你通过在浏览器中直接运行的动手代码来练习 Django Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Django Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Django Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「捕获 URL 参数」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Django Academy 课中编写并运行代码吗?

能。每节 Django Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 编写基于函数的视图
  2. 使用 path() 定义 URL 模式
  3. 捕获 URL 参数
  4. 包含应用 URL 并命名路由
← 返回 Django Academy