Search code examples
djangodjango-modelsdjango-admindjango-settingsdjango-media

How to refer to MEDIA_URL from settings.py in models.py?


I know that it is maybe not the most beautiful thing to partialy deling with view in model, but for now I would like to solve my problem this way.

in my models.py for one class I define:

def admin_image(self):
    return '<img src="/media/%s"/>' % self.thumbnail.photo
admin_image.allow_tags = True

BUT I would like that instead of hard coded /media/ there MEDIA_URL will be used, but have no idea how to call it. I am newbie to django, so please be kind :)

in my settings.py I defined:

PROJECT_ROOT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
MEDIA_ROOT = os.path.join(PROJECT_ROOT_PATH, 'media/')
MEDIA_URL = '/media/'

and in admin.py I use readonly_fields = ['admin_image'] and then I use it in list_display and fieldsets.


Solution

  • OK. I think I got it. Anyway comments how to deal with it better will be apriciated.

    in models.py:

    from django.conf import settings
    
    def admin_image(self):
        return '<img src="'+settings.MEDIA_URL+'%s"/>' % self.thumbnail.photo
    admin_image.allow_tags = True