How to build full url of object in django template using `obj.get_absolute_url'?

814 Views Asked by At

I am trying to feed "sharethis" data-url with the full url (domain + absolute_url) of the object. Currently, I am doing this in django template:

<div class="sharethis-inline-share-buttons" data-url="http://www.my-domain.com{{program.get_absolute_url}}"></div>

However, I want a better method to get this part:

http://www.my-domain.com

The reason I am looking for this is that the first method does not return a relevant url in development using localhost. it would return, as an example, this (fictional) url:

http://www.my-domain.com/objects/object_slug-object_pk/

while I expect this:

127.0.0.1.com:8000/objects/object_slug-object_pk/
1

There are 1 best solutions below

4
James Birkett On BEST ANSWER

To use the sites framwork add the following to the settings.py file.

...
SITE_ID = 1

INSTALLED_APPS = [
  ...
  'django.contrib.sites',
]

Then run python manage.py migrate This will create the database table 'django_site' the table has 3 columns id, domain, name.

Set this so that id = 1, domain='127.0.0.1:8000', name='Test Server' on your local copy and id = 1, domain='www.my-domain.com', name='my-domain' on the live server.

This should then allow you to use the following in your views.

from django.contrib.sites.models import Site
from django.shortcuts import render

full_url = 'https://%s' % (Site.objects.get_current().domain)


return render(request, 'template.html', {'domain': domain, })

in the template use

<div class="sharethis-inline-share-buttons" data-url="{{domain}}{{program.get_absolute_url}}"></div>