我懒得做一个花哨的路径转换器,所以我只是将它捕获为一个字符串并将其转换为视图中的整数(通过一些基本的完整性检查以确保该值可以正确地转换为整数):
urls.py
urlpatterns = [
path('account/<str:code>/', views.account_code),
...
]
views.py(新)
基于功能的视图 (FBV) 示例:
from django.http import HttpResponseNotFound
def your_view(request, code):
try:
code = int(self.kwargs['code'])
except ValueError:
# produces HTTP status code 404: Not Found
return HttpResponseNotFound(
"'code' must be convertible to an integer.")
基于类的视图 (CBV) 示例:
from django.http import HttpResponseNotFound
from django.views.generic import TemplateView
class CodeView(TemplateView):
def dispatch(self, request, *args, **kwargs):
try:
code = int(self.kwargs['code'])
except ValueError:
# produces HTTP status code 404: Not Found
return HttpResponseNotFound(
"'code' must be convertible to an integer.")
return super().dispatch(request, *args, **kwargs)
如果您希望用户知道发生了客户端错误,您可以将 HttpResponseNotFound 替换为 HttpResponseBadRequest,这将给出 HTTP 状态代码 400(错误请求)
编辑:下面的版本会产生一个服务器错误 HTTP 响应代码,可能是不可取的(可能会出现在错误日志等中)
views.py(旧的,由于历史原因留在这里)
try:
code = int(self.kwargs['code'])
except ValueError:
# produces HTTP status code 500: Internal Server Error
raise ValueError("'code' must be convertible to an integer.")