Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django full url in get_absolute_url

Tags:

django

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
like image 273
Ronnie Beltran Avatar asked Oct 22 '10 05:10

Ronnie Beltran


2 Answers

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)
like image 108
aladagemre Avatar answered Oct 18 '22 18:10

aladagemre


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.

like image 31
Y.N Avatar answered Oct 18 '22 19:10

Y.N