I am building a forum. When processing urls there is a board id and a board name. The name is for readability and the id is what fetches the board. This means if the name is wrong or has changed I want to redirect the user to the proper url. Some searching has led me to decorators but I cannot find any resource teaching me how to use them.
# 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})
How would I implement the following logic in a decorator?
board = Board.objects.all().get(pk=pk)
if (board.name != name):
return redirect(request.get_full_path().replace(name, board.name, 1))
After some guesswork, help from my brother and stumbling across some lucky posts I've figured it out:
# 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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With