Django:使用 {% url %} 查找视图 URL 的一部分
我无法仅获取带有 {% url %}
标记的 URL 的一部分。
URL 设置包含以下内容:
url("^delete/(?P<uuid>[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/$",
deleteView,
name = "delete"),
这意味着通过 UUID 删除项目(如您所见,视图采用参数“uuid”)。由于我不想在 URL 映射更改时更改所有模板,因此我使用命名 URL(本例中为“删除”)。
然后在模板中,我想通过 AJAX 访问该 URL,但需要使用 JavaScript 提供 UUID 参数,所以实际上我只需要 URL 的 /delete/
部分。我当前的解决方案是这样的:
uuid = "some uuid that should be deleted on the server";
$.get("{% url myinstancenamespace:delete "00000000-0000-0000-0000-000000000000" %}"
.replace("00000000-0000-0000-0000-000000000000", uuid),
function(data)
{
// process server response
}, "text");
这对我来说更像是一种黑客攻击。那么,还有比这更好的解决方案吗?
I'm having trouble getting only a part of an URL with the {% url %}
tag.
The URL setup contains this:
url("^delete/(?P<uuid>[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/$",
deleteView,
name = "delete"),
which means to delete an item by its UUID (the view takes a parameter "uuid" as you can see). As I don't want to change all templates when the URL mappings change, I'm using named URLs ("delete" in this example).
Then in the template, I want to access that URL via AJAX but need to provide the UUID parameter using JavaScript, so really I only need the /delete/
part of the URL. My current solution is this:
uuid = "some uuid that should be deleted on the server";
$.get("{% url myinstancenamespace:delete "00000000-0000-0000-0000-000000000000" %}"
.replace("00000000-0000-0000-0000-000000000000", uuid),
function(data)
{
// process server response
}, "text");
This seems more like a hack to me. So, are there any better solutions than this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我必须说,这对我来说听起来并不完全是黑客行为。
但如果您确实不想这样做,一种选择是在 URLconf 中将
uuid
参数设置为可选,方法是在其前面加上?:
前缀。当然,您需要在视图中进行更多验证,以确保您确实拥有 uuid。It doesn't sound completely hackish to me, I must say.
But if you really don't want to do it like that, one option would be to make the
uuid
parameter optional in the URLconf, by prefixing it with?:
. Of course you'd then need to do a bit more validation in the view to ensure that you actually did have a uuid.