首页 > 解决方案 > URL 中带有 slug 的 Django RedirectView

问题描述

我正在RedirectView使用 Django,我想知道如何在我的 url 中传递一个 slug。

在我的 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')

问题 :

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

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

我怎么能考虑到code我的网址而不是(?P<code>[%5Cw%5C.-]+)

谢谢

标签: regexdjangodjango-urls

解决方案


You can subclass the RedirectView for that:

# 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())

and then use it as:

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

It would however be advisable to obtain the URL of the redirect by the name of the view, for example with reverse [Django-doc], since now the URL is hardcoded and if you later deploy your application, or change the hostname, it will result in wrong redirects.

Furthermore in Django one typically does not pass much data through GET parameters, so perhaps it is better to make a view, and encode that part in the URL path, instead of the querystring.


推荐阅读