I'm using Django 2.0
In my application's models.py file I have defined get_absolute_url()
to get the absolute URL of the instance.
This model class is used as URL shortener and stores a short_key
.
This will produce url like
http://short_domain/key
the short url host domain can bet set from settings.
If the SHORT_URL_HOST
exists in settings
, that will be used otherwise current website domain/host will be used.
I'm using {{ instance.get_absolute_url }}
to display the generated short url.
from django.conf import settings
from django.http import request
class ShortUrl(models.Model):
short_key = models.CharField(max_length=25, blank=True)
def get_absolute_url(self):
reverse_url = reverse('short-url', kwargs={'key': self.short_key})
if hasattr(settings, 'SHORT_URL_HOST'):
url_host = settings.SHORT_URL_HOST
else:
url_host = request.build_absolute_uri("/").rstrip("/")
return url_host + reverse_url
If
is working fine. But in else
statement, I want to get complete URI
of current host concatenated with the reverse URL.
But this gives error as
module 'django.http.request' has no attribute 'build_absolute_uri'
How can I return full absolute URI with domain name from model's get_absolute_url(self)
function?