将 URL 中传递的额外参数设为可选

Make extra parameters passed in URL as optional

我有这个URLpath('user/delete/<int:pk>/', views.UserDeleteView.as_view(), name='delete_user'),

通过传递要由 DeleteView 访问的用户的 pk 来删除选定的用户。但是,我想通过使用带有复选框的表单来删除多个用户。为此,我使用了一个单独的视图。

我的问题是,有什么方法可以使这个 <int:pk> 作为可选参数,以便我可以对 POST 和 GET 请求使用相同的视图。以防万一我想对同一个 URL 使用 POST 方法。这可以做到吗?有人说可以在 Rails 上的 Ruby 中选择完成。在 Django 中有什么方法可以做到这一点吗?

你可以定义两个路径,一个有主键,另一个没有主键:

path('user/delete/', views.UserDeleteView.as_view(), name='delete_user'),
path('user/delete/<int:pk>/', views.UserDeleteView.as_view(), name=<b>'delete_user_id'</b>),

因此我们这里有两个视图:'delete_user' 不带 pk'delete_user_id' 带主键。两者都指向相同的 UserDeleteView.

您可以使用 kwargs= 参数为缺少的参数注入一个值:

path('user/delete/', views.UserDeleteView.as_view(), name='delete_user'<b>, kwargs={'pk': None}</b>),
path('user/delete/<int:pk>/', views.UserDeleteView.as_view(), name='delete_user_id'),

也就是说,使用 GET 请求应该没有副作用。这就是 HTTP protocol [wiki] 的设计方式:

The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect. (This is also true of some other HTTP methods.) The W3C has published guidance principles on this distinction, saying, "Web application design should be informed by the above principles, but also by the relevant limitations.".

W3组织也有guidelines when to use GET or POST:

Use GET if:

  • The interaction is more like a question (i.e., it is a safe operation such as a query, read operation, or lookup).

Use POST if:

  • The interaction is more like an order, or
  • The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or
  • The user be held accountable for the results of the interaction.

如果要删除项目,通常会发出 DELETE 或 POST 请求。例如 Django 将使用 CSRF 令牌保护此类请求,以防止 cross-site request forgery [wiki].

因此,我强烈建议您只允许 POST/DELETE 请求这些视图,当然要额外检查用户是否有权进行更改。