1

I have a function that is run every view to correct slugs. For example if the slug is /12-post-about-stuff and a user enters /12-post-abot_stof they will be redirected correctly. The problem is that the different views have different url patterns for example:

/posts/post_slug/
...
/posts/post_slug/comments/new

how to I write a function that redirects by fixing the slug name based on the current url?

Edit: I am applying a decorator to every view with a board_name and pk argument. What I don't know is how to dynamically return the new url because the url format is different for each view.

def correct_board_url_name(func):
  def wrapper(request, board_slug):
        try:
            pk = int(board_slug.split('-')[0])
            board = Board.objects.get(pk=pk)
            if (board.slug != board_slug):
                # This does not always work depending on what is entered
                return redirect(request.get_full_path().replace(board_slug, board.slug, 1))
            else:
                return func(request, board_slug)
        except:
            raise Http404('')
    return wrapper

1 Answers1

2

A middleware is a good choice if you want to process requests in many different views.

class RedirectMiddleware(object):
    def process_request(self, request):
        if request.resolver_match.app_name == 'posts' \
                and 'post_slug' in request.resolver_match.kwargs: 
            new_path = None
            # your logic here
            if new_path:
                return redirect(new_path, permanent=True)
        return

In settings:

MIDDLEWARE = [
    # another middlewares here ...
    'path.to.RedirectMiddleware',
]
Anton Shurashov
  • 1,820
  • 1
  • 26
  • 39