Django RedirectView缺少变量(Django RedirectView with missing variables)

编程入门 行业动态 更新时间:2024-10-28 04:16:47
Django RedirectView缺少变量(Django RedirectView with missing variables)

您好我想将/{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

本文发布于:2023-08-07 21:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465913.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   RedirectView   Django   missing   variables

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!