views:

122

answers:

1

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?

+1  A: 

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.

Daniel Roseman
Then I would have to reparse the URL in the view, which leads to another place that must know the URLconf. So that's another (bigger) hack IMO.
AndiDog
Not at all. The uuid would still be passed in as a parameter, but the function signature would be `def deleteView(request, uuid=None):` and you would just need to check `if uuid is None`.
Daniel Roseman
Could you please edit your answer to include the full regex, I think I don't get what exactly you mean (doesn't work the way I interpret your answer ;).
AndiDog