regex - URL 中带有 slug 的 Django RedirectView
问题描述
我正在RedirectView
使用 Django,我想知道如何在我的 url 中传递一个 slug。
在我的 Django Web 应用程序中,用户可以在购物车中设置一个或多个文档,并在提交表单之前打开带有个人信息的模式并收到一封包含已检查文档的电子邮件。
我的应用程序中的这个 url 看起来像这样:
http://localhost:8000/freepub/home?DocumentChoice=<code>&DocumentSelected=Add+document
<code>
对应于唯一的文档代码(例如:PUBSD15-FR-PDF
或PUBSD01-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.-]+)
?
谢谢
解决方案
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.
推荐阅读
- python - 凸面缺陷分析中的缺失点
- java - *.json.swp 的 com.fasterxml.jackson.core.JsonParseException?
- scapy - scapy 中的过滤命令不起作用,我在 Windows 中运行
- java - Java Hangman Game(主要关注输出)
- php - CodeIgniter:没有从外部文件应用 CSS
- python - 从 python-gtk2 迁移到 python-gi
- laravel - Laravel 输入数组更新与单次提交
- javascript - 有没有办法在 node.js 中创建延迟?
- firebase - vuejs + Firebase 删除/更新孙子
- php - php simplexml在循环中添加子节点