Django: Finding part of a view's URL using {% url %}
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?
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.
精彩评论