网址中有slug的Django RedirectView

时间:2018-10-31 10:59:45

标签: regex django django-urls

我在Django中获得RedirectView,我想知道如何在我的网址中传递一个标签。

在我的Django Web应用程序中,用户可以在购物车中设置一个或多个文档,并打开一个包含个人信息的模式,然后再提交表单并获得包含已检查文档的电子邮件。

我的应用程序中的该URL如下所示:

http://localhost:8000/freepub/home?DocumentChoice=<code>&DocumentSelected=Add+document

<code>对应于唯一的文档代码(例如:PUBSD15-FR-PDFPUBSD01-EN-EPUB

但是此url有点复杂,因为应该将其添加到另一个应用程序中。

这就是为什么我使用RedirectView来简化此URL的原因:

url(r'^freepub/direct/download/(?P<code>[\w\.-]+)/', 
       RedirectView.as_view(url="http://localhost:8000/freepub/home?DocumentChoice=(?P<code>[\w\.-]+)&DocumentSelected=Add+document"),
       name='go-to-direct-download')

问题:

如果我在URL中写:http://localhost:8000/freepub/direct/download/PUBSD15-FR-PDF

重定向为:http://localhost:8000/freepub/home?DocumentChoice=(?P<code>[%5Cw%5C.-]+)&DocumentSelected=Add+document

如何考虑URL中的code而不是(?P<code>[%5Cw%5C.-]+)

谢谢

1 个答案:

答案 0 :(得分:2)

您可以为此而将RedirectView子类化:

# app/views.py

from django.http import QueryDict

class MyRedirectView(RedirectView):

    def get_redirect_url(self, *args, **kwargs):
        q = QueryDict(mutable=True)
        q['DocumentChoice'] = self.kwargs['code']
        q['DocumentSelected'] = 'Add document'
        return 'http://localhost:8000/freepub/home?{}'.format(q.urlencode())

,然后将其用作:

url(
    r'^freepub/direct/download/(?P<code>[\w\.-]+)/', 
    MyRedirectView.as_view(),
   name='go-to-direct-download'
),

但是,建议使用视图名称来获取重定向的URL,例如使用reverse [Django-doc],因为现在URL是硬编码的,并且如果您以后部署应用程序或更改主机名,将会导致错误的重定向。

此外,在Django中,通常不会通过GET参数传递大量数据,因此也许最好创建一个视图并将该部分编码在URL路径中,而不是查询字符串。