[ACCEPTED]-How can I get the Django admin's "View on site" link to work?-django-sites

Accepted answer
Score: 15

Define a get_absolute_url on your model. The admin uses 2 that method to figure out how to construct 1 the objects url. See the docs.

Score: 9



into your INSTALLED_APPS and a following 3

$ ./manage.py syncdb

may suffice.

When installed, edit the Site 2 instance (e.g. through /admin interface) to reflect 1 your local hostname (e.g. localhost:8000).

Score: 5

As communicated by others, this requires 8 a couple extra steps in addition to enabling 7 view_on_site. You have to implement get_absolute_url() in 6 your model, and enable Sites in your project 5 settings.

Set the view_on_site setting

Add view_on_site setting to admin 4 form:

class MymodelAdmin(admin.ModelAdmin):
    view_on_site = True
admin.site.register(Mymodel, MymodelAdmin)

Implement get_absolute_url()

Add get_absolute_url() to your model. In models.py:

    def get_absolute_url(self):
        return "/mystuff/%i" % self.id

Enable Sites

Add 3 Sites in yourapp/settings.py:


Then update 2 the database:

$ python manage.py migrate


Check out reverse() for a more sophisticated 1 way to generate the path in get_absolute_url().

Score: 1

It seems to me that the view on site functionality 9 works only if get_absolute_url refares to a Django view. It 8 does not seem to work if you are trying 7 to create a link, which redirects to a page 6 out of Django's control (even if it is served 5 from the same domain by apache itself).

In 4 this case, it is easy to create the button 3 manually by overriding admin tempale as 2 follows:

{% extends "admin/change_form.html" %}
{% block object-tools-items %}
{{ block.super }}
    <a class="viewsitelink" href="{{ original.get_absolute_url }}">View on my site, out of Django's control</a>
{% endblock %}

Also, add view_on_site = False to your ModelAdmin class, otherwise 1 both of the buttons will appear.

Score: 1

According to the Django documentation, and 6 as of Django 3.1 (May 2020), you have to 5 define a get_absolute_url() method in your 4 model.

One place Django uses get_absolute_url() is 3 in the admin app. If an object defines this method, the object-editing page will have a “View on site” link that will jump you directly to the object’s public view, as 2 given by get_absolute_url().

Here is an example 1 from the documentation:

def get_absolute_url(self):
        from django.urls import reverse
        return reverse('people.views.details', args=[str(self.id)])

Source: https://docs.djangoproject.com/en/3.1/ref/models/instances/#get-absolute-url

Score: 0

When you have edited either SITE_ID in settings.py 3 or a Site instance thought the admin, don't 2 forget to restart your web server for the 1 change to take effect.

More Related questions