URL 中带有 slug 的 Django RedirectView

Django RedirectView with slug in the URL

我正在使用 Django RedirectView,我想知道如何在我的 url.

中传递 slug

在我的 Django 网络应用程序中,用户可以在购物车中设置一个或多个文档,并在提交表单之前打开一个包含个人信息的模式,并收到一封包含选中文档的电子邮件。

我的应用程序中的 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.-]+)

谢谢

您可以为此 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 路径中,而不是查询字符串中。