0

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?

Anuj TBE
  • 9,198
  • 27
  • 136
  • 285
  • 2
    Your model doesn't (shouldn't) know anything about requests, that should be handled in the view layer. Indeed where does `request` even come from in this method? If you want to do conditional redirection you should do that in the view and you'll have a request object in scope. – jhrr Dec 15 '17 at 19:59
  • I thought of that importing django request might work. I want `{{ instance.get_absolute_url }}` to print full url including domain in the template – Anuj TBE Dec 15 '17 at 20:18
  • Why don't you expand the detail of your question to show more of what it is you are trying to achieve. Post: model, view, template (fragments) and summarise the issue. There will be a solution to your problem but I suspect you are kind of swimming against the current of how Django works. – jhrr Dec 15 '17 at 20:22
  • I have summarised the question a little. Hope it will make some sense. – Anuj TBE Dec 15 '17 at 20:30
  • @jhrr What about the case when sending an email from signals or model method and you want a link for the user to change a specific model? – tread Jan 04 '18 at 11:38

0 Answers0