我正在努力建立论坛。处理网址时,有一个主板ID和一个主板名称。电路板名称仅用于用户可读性,这意味着如果有人正确输入了ID,但电路板名称错误或已更改,则会将它们重定向到正确的URL。我创建了一个管理它的函数,因为我需要多次检查电路板是否正确,而不仅仅是这个网址。
# urls.py
...
url(r'^boards/(?P<board_id>\d+)/(?P<board_name>[^/]+)/$', views.board, name='board'),
...
# views.py
def board(request, board_id, board_name):
RedirectIfWrong(request, board_id, board_name)
...
return render(request, 'forums/board.html', {'board': board})
def RedirectIfWrong(request, pk, name):
board = Board.objects.all().get(pk=pk)
if (board.name != name):
return redirect(request.get_full_path().replace(name, board.name, 1))
然而,当我在函数内部调用重定向时,它不起作用。我也听说过使用中间件来做到这一点。这是如何工作的,我如何使它只适用于涉及董事会的网址?
答案 0 :(得分:2)
def board(request, board_id, board_name):
bad = RedirectIfWrong(request, board_id, board_name)
if bad:
return bad
...
return render(request, 'forums/board.html', {'board': board})
答案 1 :(得分:1)
添加回报
def board(request, board_id, board_name):
return RedirectIfWrong(request, board_id, board_name)
# ^^^^