Django编写自定义装饰器

时间:2017-07-30 06:16:09

标签: python django

我正在建立一个论坛。处理网址时,有一个主板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))

1 个答案:

答案 0 :(得分: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})