Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django writing a custom decorator

Tags:

python

django

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))
like image 713
Settings Menu Hard to Find Avatar asked Nov 07 '22 18:11

Settings Menu Hard to Find


1 Answers

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})
like image 116
Settings Menu Hard to Find Avatar answered Nov 15 '22 04:11

Settings Menu Hard to Find