Django redirect inside a function

Viewed 952

I am trying to build forum. When processing urls there is a board id and a board name. The board name exists just for user readability meaning if someone enters the id correctly but the board name is wrong or has changed it will redirect them to the correct url. I created a function to manage this because there are multiple times I need to check if the board is right, not just this one 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))

However when I call redirect inside a function it does not work. I have also heard of using middleware to do this. How does that work and how do I make it only apply to urls involving a board?

2 Answers
Related