您好我想将/{category}/{sub_category}等网址重定向到/{category}/但RedirectView希望使用子类别和类别关键字参数解析网址
url(r'^/(?P<category_slug>[^\/]+)/$', CategoryView.as_view(), name='category'), url(r'^/(?P<category_slug>[^\/]+)/(?P<another_parameter>[^\/]+)$', RedirectView.as_view(pattern_name='category')),所以这不起作用,我认为默认应该忽略不需要的参数..
我得到django.urls.exceptions.NoReverseMatch:
什么是使这项工作的最佳选择?
Hello I want to redirect the urls like /{category}/{sub_category} to /{category}/ but RedirectView wants to resolve the url with both subcategory and category keyword arguments
url(r'^/(?P<category_slug>[^\/]+)/$', CategoryView.as_view(), name='category'), url(r'^/(?P<category_slug>[^\/]+)/(?P<another_parameter>[^\/]+)$', RedirectView.as_view(pattern_name='category')),so this doesn't work, I think default should be ignoring unrequired parameters..
I am getting django.urls.exceptions.NoReverseMatch:
What would be the best option to make this work?
最满意答案
当你使用pattern_name ,Django将尝试使用与传入视图相同的args和kwargs进行反转。 这不适合您,因为您想要重定向到仅采用category_slug的category视图。
您可以get_success_url RedirectView并覆盖get_success_url 。
from django.urls import reverse class CategoryRedirectView(RedirectView): def get_redirect_url(self): return reverse('category', args=(self.kwargs['category'],))然后在您的网址中使用CategoryRedirectView而不是RedirectView 。
url(r'^(?P<category_slug>[^\/]+)/(?P<another_parameter>[^\/]+)$', CategoryRedirectView.as_view()),请注意,我删除了前导斜杠。 您只需要使用include()而不使用尾部斜杠。 你绝对不需要根URL url中的前导斜杠。
When you use pattern_name, Django will try to reverse with the same args and kwargs as were passed in to the view. This doesn't work for you, because you want to redirect to the category view which only takes category_slug.
You can subclass RedirectView and override get_success_url.
from django.urls import reverse class CategoryRedirectView(RedirectView): def get_redirect_url(self): return reverse('category', args=(self.kwargs['category'],))Then use CategoryRedirectView in your urls instead of RedirectView.
url(r'^(?P<category_slug>[^\/]+)/(?P<another_parameter>[^\/]+)$', CategoryRedirectView.as_view()),Note that I've removed the leading slash. You would only need it you are using include() without a trailing slash. You definitely don't need the leading slash in the root url conf.
更多推荐
RedirectView,category,urls,url,电脑培训,计算机培训,IT培训"/> <meta name=&quo
发布评论