Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display model URL in admin

I've got a couple of models. Neither have any list view other than their admin entries. For that reason, it's a bit of a pain to manually work out the URLs for model instances.

I would like to show a link on the listing and detail admin views that takes me directly to the public view. I can do the nonsense that works creates the URL but I don't know how to get it to show in the admin.

Any ideas?

like image 412
Oli Avatar asked Jun 05 '09 15:06

Oli


People also ask

How do I show all fields of model in admin page?

If my model has (username, age, gender, fav_genre, warning), I use "def __unicode__(self): return self. username + self. fav_genre" and this will show me whatver is returned.

How do I find my Django admin URL?

Open a browser on the Django admin site http://127.0.0.1:8000/admin/.

What is admin panel in Django?

One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.


2 Answers

show_url.allow_tags = True didn't work for me. I had to use mark_safe:

from django.urls import reverse
from django.utils.safestring import mark_safe

class MyAdmin(admin.ModelAdmin):
    list_display=('name', 'detail_url')

    def detail_url(self, instance):
        url = reverse('url_name')    
        return mark_safe(f'<a href="{url} target="_blank" rel="nofollow"">Follow</a>')
like image 180
Valery Ramusik Avatar answered Oct 17 '22 15:10

Valery Ramusik


If the model has a get_absolute_url() method, there should automatically be a 'View on site' button at the top right of the admin detail screen.

For the list view, you can easily add a method to the list of fields shown:

class MyAdmin(admin.ModelAdmin):
    list_display=('name', 'anotherfield', 'show_url')

    def show_url(self, instance):
        return '<a href="%s">View on site</a>' % (instance.get_absolute_url())
    show_url.allow_tags = True
like image 42
Daniel Roseman Avatar answered Oct 17 '22 16:10

Daniel Roseman