1
votes

You know how in a Django app, you can redirect to a different view using a simple function in your views? Its usually something like this:

return redirect('myapp:my_url')

The above redirect would redirect me to an absolute URL which could be something like this:

https://example.com/my-url/

Now, my question is, how can I get the https://example.com/my-url/ as a string using a function in my view? I don't want to redirect, I just want to get it, and save it in my variable.

So, by doing something like this:

print my_function('myapp:my_url')

We would get an output in the terminal like so:

https://example.com/my-url/

Any help? Thanks!

1

1 Answers

1
votes

You can get the "path" element of the URL (ie /my-url/) using the reverse function you have already mentioned.

The domain of the website can be added using request.build_absolute_uri().

print(request.build_absolute_uri(reverse('myapp:my_url'))

Note that I'm using the Python 3 print syntax for this example.