Django url解析-传递原始字符串
我正在尝试将“字符串”参数传递给带有网址的视图。 urls.py
('^add/(?P<string>\w+)', add ),
出现了字符串问题,包括标点符号、换行符、空格等。 我想我必须将 \w+ 更改为其他内容。 基本上,该字符串将是用户从他选择的文本中复制的内容,我不想更改它。我想接受任何字符和特殊字符,以便视图完全按照用户复制的内容起作用。
我怎样才能改变它?
谢谢!
I'm trying to pass a 'string' argument to a view with a url.
The urls.py goes
('^add/(?P<string>\w+)', add ),
I'm having problems with strings including punctuation, newlines, spaces and so on.
I think I have to change the \w+ into something else.
Basically the string will be something copied by the user from a text of his choice, and I don't want to change it. I want to accept any character and special character so that the view acts exactly on what the user has copied.
How can I change it?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请注意,您只能使用可以被理解为正确 URL 的字符串,将任何字符串作为 url 传递并不是一个好主意。
我使用此正则表达式允许在我的网址中使用字符串值:
这允许有“slugs;”在您的网址中(例如:'this-is-my_slug')
Notice that you can use only strings that can be understood as a proper URLs, it is not good idea to pass any string as url.
I use this regex to allow strings values in my urls:
This allows to have 'slugs; in your url (like: 'this-is-my_slug')
首先,URL 中不允许使用很多字符。对于初学者来说,想想
?
和空格。无论您做什么,Django 都可能会阻止这些内容传递到您的视图。其次,您需要阅读 re 模块。它用于设置这些 URL 匹配的语法。
\w
表示任何大写或小写字母、数字或_
(基本上是标识符字符,但它不允许使用前导数字)。将字符串传递到 URL 的正确方法是作为表单参数(即 URL 中的
?paramName=
之后,并转义特殊字符,例如将空格更改为+)。
Well, first off, there are a lot of characters that aren't allowed in URLs. Think
?
and spaces for starters. Django will probably prevent these from being passed to your view no matter what you do.Second, you want to read up on the re module. It is what sets the syntax for those URL matches.
\w
means any upper or lowercase letter, digit, or_
(basically, identifier characters, except it doesn't disallow a leading digit).The right way to pass a string to a URL is as a form parameter (i.e. after a
?paramName=
in the URL, and with special characters escaped, such as spaces changed to+
).