29

I added a get_absolute_url function to one of my models.

def get_absolute_url(self):
    return '/foo/bar' 

The admin site picks it up and adds a "view on site" link to the detail page for that object (when I put a real URL there instead of "/foo/bar").

The problem is instead of going to http://localhost:8000/foo/bar, it goes to http://example.com/foo/bar.

What am I doing wrong?

Paco
  • 4,520
  • 3
  • 29
  • 53
Patrick McElhaney
  • 57,901
  • 40
  • 134
  • 167
  • [Thom Wiggers](https://stackoverflow.com/a/26947339) provides really eloquent solution to the problem – Carel Jan 22 '19 at 07:04

6 Answers6

27

You have to change default site domain value.

Alex Koshelev
  • 16,879
  • 2
  • 34
  • 28
  • 7
    Thanks. It took me a while to figure out how to do that. It's an entry in the django_site table. I found and changed it by clicking on "Sites" in the admin. – Patrick McElhaney Dec 05 '08 at 20:12
6

The funniest thing is that "example.com" appears in an obvious place. Yet, I was looking for in in an hour or so.

Just use your admin interface -> Sites -> ... there it is :)

Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83
4

As others have mentioned, this is to do with the default sites framework.

If you're using South for database migrations (probably a good idea in general), you can use a data migration to avoid having to make this same database change everywhere you deploy your application, along the lines of

from south.v2 import DataMigration
from django.conf import settings

class Migration(DataMigration):

    def forwards(self, orm):
        Site = orm['sites.Site']
        site = Site.objects.get(id=settings.SITE_ID)
        site.domain = 'yoursite.com'
        site.name = 'yoursite'
        site.save()
supervacuo
  • 9,072
  • 2
  • 44
  • 61
4

You can change this in /admin/sites if you have admin enabled.

2

If you are on newer versions of django. the data migration is like this:

from django.conf import settings
from django.db import migrations

def change_site_name(apps, schema_editor):
    Site = apps.get_model('sites', 'Site')
    site = Site.objects.get(id=settings.SITE_ID)
    site.domain = 'yourdomain.com'
    site.name = 'Your Site'
    site.save()

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(change_site_name),
    ]
Xerion
  • 3,141
  • 5
  • 30
  • 46
1

When you have edited a Site instance thought the admin, you need to restart your web server for the change to take effect. I guess this must mean that the database is only read when the web server first starts.

Gary Robertson
  • 494
  • 4
  • 5