gpt4 book ai didi

python - Django 编写自定义装饰器

转载 作者:太空狗 更新时间:2023-10-30 01:32:06 24 4
gpt4 key购买 nike

我正在建立一个论坛。处理 url 时,有一个板 ID 和一个板名称。名称是为了便于阅读,而 id 是用来获取板的。这意味着如果名称错误或已更改,我想将用户重定向到正确的 url。一些搜索让我找到了装饰器,但我找不到任何资源教我如何使用它们。

# urls.py
...
url(r'^boards/(?P<board_id>\d+)/(?P<board_name>[^/]+)/$', views.board, name='board'),
...

# views.py
@redirect_if_wrong_boardname
def board(request, board_id, board_name):
...
return render(request, 'forums/board.html', {'board': board})

如何在装饰器中实现以下逻辑?

board = Board.objects.all().get(pk=pk)
if (board.name != name):
return redirect(request.get_full_path().replace(name, board.name, 1))

最佳答案

经过一些猜测,在我兄弟的帮助下,偶然发现了一些幸运的帖子,我已经弄明白了:

# views.py
def redirect_if_wrong_boardname(func):
def wrapper(request, board_id, board_name):
try:
board = Board.objects.get(pk=board_id)
if (board.name != board_name):
return redirect('/boards/' + board.pk + '/' + board.name)
else:
return func(request, board_id, board_name)
except:
return Http404('Board not found')
return wrapper

@redirect_if_wrong_boardname
def board(request, board_id, board_name):
...
return render(request, 'forums/board.html', {'board': board})

关于python - Django 编写自定义装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45396953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com