我有一个运行每个视图的功能来纠正slu .. 例如,如果slug是/ 12-post-about-stuff并且用户输入/ 12-post-abot_stof,则它们将被正确地重定向。问题是不同的视图具有不同的url模式,例如:
/posts/post_slug/
...
/posts/post_slug/comments/new
如何根据当前网址修改slug名称来编写重定向的函数?
编辑:我正在使用board_name和pk参数为每个视图应用装饰器。我不知道的是如何动态返回新网址,因为每个视图的网址格式都不同。
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
答案 0 :(得分:2)
如果您想在许多不同的视图中处理请求,中间件是一个不错的选择。
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
在设置中:
MIDDLEWARE = [
# another middlewares here ...
'path.to.RedirectMiddleware',
]