Search code examples
djangopermalinks

How do a specify get_absolute_url() on a view when the model isn't clear?


I have a place in my Django app where I need to construct a callback to my domain after a third-party auth, but I'm stuck on how to do this since that view in question doesn't really map to one model (or rather, the view code references multiple models), and the docs for get_absolute_url() construction and permalinks all reference models.

For instance, in my template I currently have something like:

<a class="btn btn-danger large" href="http://to/third/party?api_key=noneyobiz&cb=http://localhost:8000/signup">Join via Somethingorother</a>

the line for this view in urls.py is:

    url(r'^signup/$', 'signup', name="signup"),

I want the hardcoded 'http://localhost:8000/signup' to be dynamic. I'm hoping this functionality doesn't depend on my using generic views. Actually I don't understand why generating a permalink is even tied to models at all, it seems like it should only depend on the urlconf. What am I missing here?


Solution

  • permalink is a thin wrapper of django.core.urlresolvers.reverse. Its belongs to django.db.models to be a shortcut because we usually write reverse inside get_absolute_url of models. So use reverse here

    from django.core.urlresolvers import reverse
    path = reverse('signup')
    

    Update

    To use absolute URI, you could

    • hardcode in settings or use something like Site.objects.get_current() w/ the path you get from reverse or url to get the absolute URI, as Daniel suggested.
    • If your callback URI is in the same domain w/ the view rendering the template, you could rely on request to get actual absolute URI:

      request.build_absolute_uri(reverse('signup'))

    Furthermore, you may want to escape the URI in template, like {{ absolute_uri|urlencode }}. or in view through urllib.quote or urllib.urlencode