I want to have a absolute/complete url when i call my models get_absolute_url method in template. in my entry model i have below:
def get_absolute_url(self):
return ('blog_entry_detail', (), { 'year': self.pub_date.strftime("%Y"),
'month': self.pub_date.strftime("%b").lower(),
'day': self.pub_date.strftime("%d"),
'slug': self.slug })
get_absolute_url = models.permalink(get_absolute_url)
in my template file:
{{object.get_absolute_url}}
I want to output the url prepended with 'http://www.example.com'
I want to use below lines to get the current domain name but i dont know where will i put it.
from django.contrib.sites.models import Site
current_site = Site.objects.get_current().domain
This might work for you:
class Article(models.Model):
...
...
def get_absolute_url(self):
path = reverse('display_article', args=[self.slug])
return "http://%s%s" % (self.site, path)
My solution, with Sites framework
In API\views.py
class NotificationSerializer(serializers.HyperlinkedModelSerializer):
absolute_url = serializers.CharField(source='get_full_absolute_url', read_only=True)
class Meta:
model = Notification
fields = ( 'id', 'created_at', 'msg_txt', 'url', 'absolute_url' )
In models.py
from django.contrib.sites.models import Site
class Notification(models.Model):
sender_user = models.ForeignKey(User, related_name = 'sender_user' )
created_at = models.DateTimeField(default=timezone.now)
reciever_user = models.ForeignKey(User, related_name = 'reciever_user')
readed_at = models.DateTimeField( blank=True, null = True )
msg_txt = models.CharField(max_length=255, blank=False)
def get_absolute_url(self):
return "/notification/%i/" % self.id
def get_full_absolute_url(self):
domain=Site.objects.get_current().domain
return 'http://%s%s' % (domain, self.get_absolute_url())
Var 2, without Sites framework
If you have not Sites framework, you can use the ALLOWED_HOSTS settings.
In models.py
from myapp.settings import ALLOWED_HOSTS
class Notification(models.Model):
...
def get_full_absolute_url(self):
domain=ALLOWED_HOSTS[0]
return 'http://%s%s' % (domain, self.get_absolute_url())
ALLOWED_HOSTS is required for production site.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With