[英]Django: redirect url if slug is wrong
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.
例如,如果该子弹是/ 12-post-about-stuff,并且用户输入/ 12-post-abot_stof,则将正确重定向它们。 The problem is that the different views have different url patterns for example:
问题在于不同的视图具有不同的URL模式,例如:
/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? 我该如何编写一个函数,该函数通过基于当前url修复子弹名称进行重定向?
Edit: I am applying a decorator to every view with a board_name and pk argument. 编辑:我将装饰器应用于具有board_name和pk参数的每个视图。 What I don't know is how to dynamically return the new url because the url format is different for each view.
我不知道如何动态返回新的url,因为每个视图的url格式都不同。
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
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',
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.