visualizing uploaded images in django admin

  • Last Update :
  • Techknowledgy :

First of all, let's suppose your django project have this architecture and you're running django 2.0:

.django_test
   |
   _ django_test |
   | _ __init__.py |
   | _ settings.py |
   | _ urls.py |
   | _ wsgi.py |
   _ media |
   | _ author_headshot |
   _ my_app |
   | _ admin.py |
   | _ __init__.py |
   | _ apps.py |
   | _ migrations |
   | _ models.py |
   | _ tests.py |
   | _ urls.py |
   | _ views.py |
   _ static |
   _ templates

Then, add in your django_test/settings.py :

# static files will be stored in 'static'
folder
STATIC_URL = '/static/'
STATICFILES_DIR = [
   BASE_DIR + '/static'
]
# media files will be stored in 'media'
folder
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR + '/media'

Then, in django_test/urls.py make sure to add the static path of your MEDIA_URL and MEDIA_ROOT like this example:

from django.contrib
import admin
from django.conf
import settings
from django.conf.urls.static
import static
from django.urls
import path

urlpatterns = [
   path('admin/', admin.site.urls),
   # More paths / urls
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

Then, in my_app/admin.py :

from django.contrib
import admin
from.import models

@admin.register(models.Author)
class AuthorAdmin(admin.ModelAdmin):
   list_display = ('image_tag', )

admin.py

from django.contrib import admin
from .models import Image

class ImageAdmin(admin.ModelAdmin):
    list_display = ('title', 'description', 'image_display', )
    search_fields = ('title', 'description')
    list_per_page = 25

    def image_display(self, obj):
        return '<a href="/media/{0}"><img src="/media/{0}"></a>'.format(self.imagefile.url)
    image_.allow_tags = True
    image.short_descripition = u'IMAGE'

admin.site.register(Image, ImageAdmin)

def image_tag(self):
    return '<a href="{0}"><img src="{0}" width = "120" height = "120"></a>'.format(self.img1.url)
image_tag.allow_tags = True
image_tag.short_description = 'y-Image'

Make sure your src starts with 'http://', as in:

def display_image(self):
    return format_html(
        "<img src='http://127.0.0.1/8887{}'>", 
        self.image_attribute.url
)

Suggestion : 2

The images of ImageField are saved in images folder which is the directory your-project/media/images.,Your image_(self) function is pointing to one level deeper when you are using "media/{0}" i.e. it will point to your-project/media//media/images (notice the // here which is coming due to extra / of /{0}). Your functions should be modified as follows:,there is fine line when you use the ImageField and when you use the function image_(self) to make the image visible. See the diagram below: this is the link of the image as my reputation does not allow me to post image. The img1 column represents the imagefile variable you used in models.py. ,And finally, in your application model, you can add a unique folder for each ImageField where your media files will be stored like this example:


def image_tag(self):
    return '<a href="{0}"><img src="{0}" width = "120" height = "120"></a>'.format(self.img1.url)
image_tag.allow_tags = True
image_tag.short_description = 'y-Image'

Make sure your src starts with 'http://', as in:

def display_image(self):
    return format_html(
        "<img src='http://127.0.0.1/8887{}'>", 
        self.image_attribute.url
)

admin.py

from django.contrib import admin
from .models import Image

class ImageAdmin(admin.ModelAdmin):
    list_display = ('title', 'description', 'image_display', )
    search_fields = ('title', 'description')
    list_per_page = 25

    def image_display(self, obj):
        return '<a href="/media/{0}"><img src="/media/{0}"></a>'.format(self.imagefile.url)
    image_.allow_tags = True
    image.short_descripition = u'IMAGE'

admin.site.register(Image, ImageAdmin)

First of all, let's suppose your django project have this architecture and you're running django 2.0:

.django_test
   |
   _ django_test |
   | _ __init__.py |
   | _ settings.py |
   | _ urls.py |
   | _ wsgi.py |
   _ media |
   | _ author_headshot |
   _ my_app |
   | _ admin.py |
   | _ __init__.py |
   | _ apps.py |
   | _ migrations |
   | _ models.py |
   | _ tests.py |
   | _ urls.py |
   | _ views.py |
   _ static |
   _ templates

Then, add in your django_test/settings.py :

# static files will be stored in 'static'
folder
STATIC_URL = '/static/'
STATICFILES_DIR = [
   BASE_DIR + '/static'
]
# media files will be stored in 'media'
folder
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR + '/media'

Then, in django_test/urls.py make sure to add the static path of your MEDIA_URL and MEDIA_ROOT like this example:

from django.contrib
import admin
from django.conf
import settings
from django.conf.urls.static
import static
from django.urls
import path

urlpatterns = [
   path('admin/', admin.site.urls),
   # More paths / urls
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

Then, in my_app/admin.py :

from django.contrib
import admin
from.import models

@admin.register(models.Author)
class AuthorAdmin(admin.ModelAdmin):
   list_display = ('image_tag', )

Suggestion : 3

request.FILES['docfile'] can be saved to models.FileField. The model's save() handles the storing of the file to the filesystem automatically., The FileField has many attributes that can be used in templates. E.g. {{ document.docfile.url }} and {{ document.docfile.name }} as in the template. See more about these in Using files in models article and The File object documentation.,This defines a Form class with a single field (docfile) of FileField. ,To upload files and to serve them, we want to specify where Django stores uploaded files and from what URL Django serves them via two variables in settings.py: MEDIA_ROOT and MEDIA_URL. They are by default empty:

We'll run it on a local host first, and then deploy it to a shared host in another chapter (Image files uploading on a shared host). We're going to use Django 1.6.5:

$ python - c "import django; print(django.get_version())"
1.6 .5

We need to set the database we're going to use. In this example for local host, we'll use sqlite:

DATABASES = {
   'default': {
      'ENGINE': 'django.db.backends.sqlite3',
      # Add 'postgresql_psycopg2',
      'mysql',
      'sqlite3'
      or 'oracle'.
      'NAME': os.path.join(PROJECT_ROOT, 'database/database.sqlite3'),
      # Or path to database file
      if using sqlite3.
      'USER': '',
      # Not used with sqlite3.
      'PASSWORD': '',
      # Not used with sqlite3.
      'HOST': '',
      # Set to empty string
      for localhost.Not used with sqlite3.
      'PORT': '',
      # Set to empty string
      for
      default.Not used with sqlite3.
   }
}

To upload files and to serve them, we want to specify where Django stores uploaded files and from what URL Django serves them via two variables in settings.py: MEDIA_ROOT and MEDIA_URL. They are by default empty:

# Absolute filesystem path to the directory that will hold user - uploaded files.
# Example: "/home2/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')

# URL that handles the media served from MEDIA_ROOT.Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

Now we need a model with a FileField. This field stores files e.g. to media/documents/2014/07/05/ based on current date and MEDIA_ROOT. See FileField reference:

class FileField([upload_to = None, max_length = 100, ** options])

Our code:

# - * -coding: utf - 8 - * -
   from django.db
import models

class Document(models.Model):
   docfile = models.FileField(upload_to = 'documents/%Y/%m/%d')

Suggestion : 4

The default admin shows the url of the uploaded image but not the image itself.,While I can show an uploaded image in list_display is it possible to do this on the per model page?,to your ModelAdmin. If you want to restrict the ability to edit the image field, be sure to add it to the exclude attribute.,79816/how-to-show-image-from-imagefield-django-admin

A quick sample model would be:

Class Model1(models.Model):
   image = models.ImageField(upload_to = directory)

In your model class add a method like:

def image_tag(self):
from django.utils.html import escape
return u'<img src="%s" />' % escape(<URL to the image>)
   image_tag.short_description = 'Image'
   image_tag.allow_tags = True

and in your admin.py add:

fields = ('image_tag', )
readonly_fields = ('image_tag', )