Skip to content

Multiple image upload component

Lawrence Liu edited this page Jul 18, 2016 · 2 revisions
  • Files of the component

    • UI Related

      • app/views/components/image_field.py Field and Input definition, formatter of the component
      • app/templates/components/images_field.html Template of the editable component
      • app/templates/components/images_display.html Template of the readonly component
      • app/static/js/image_upload.js Javascript to do all the UI thumbnail preview etc.
      • app/static/css/style.css CSS definition.
      • app/static/lightbox2 lightbox2 library to display all images as a gallery in UI
    • Models

      • app/models/image.py Image model, contains URL/id and alt text of the field.
      • app/models/XXX_image.py The related object with image, for example, ProductImage(holds a relationship between the actual owner object and image object)
  • Related files (needed)

    • app/utils/file_util.py Code to invoke the image save service, and save the image
    • app/thirdparty/cloudinary_image_store.py Cloudinary image store service
    • app/thirdparty/local_image_store.py Local image store service(to be implemented)
    • app/service.py Set and get image store service
    • app/init.py Where the image store service got set

Usage:

  • Define two fields in the model

    1. images --> The field actually holds the link.
    2. hybrid field called images_placeholder --> The field to be used in UI and form as a placeholder for the image field.
  • Setup formatter of the field as below

column_formatters = {
    'images_placeholder': images_formatter,
}
  • Add the field images_placeholder to the object admin page via
form_extra_fields = {
    'images_placeholder': ImageField(label=lazy_gettext('XXX Images')),
}
  • Set object type of the image field in create_form and edit_form:
def create_form(self, obj=None):
    form.images_placeholder.set_object_type(XXXImage)

def edit_form(self, obj=None):
    form.images_placeholder.set_object_type(XXXImage)

Footnote:

  • The follow css defined in style.css file
#images-preview-panel img  /* Width and height of the thumbnail image for preview */
#images-preview-panel div  /* Preview panel for one image */
#images-preview-panel div span[id^=delete-] /* Delete icon in the top right corner of thumbnail */
#images-field-panel /* outermost container of the component */
#upload_text_trigger  /* Upload link button */
  • This component assumes the use of
    • Flask
    • Flask-admin
    • Flask-sqlachemely
    • SQL Database