class CategoryView(ModelView): inline_models = [ 'product', ] column_searchable_list = ('name', 'price', 'size') inline_models = ( Product, dict(form_excluded_columns=['categories'], form_extra_fields={ 'image_name': form.ImageUploadField( 'Image', base_path='templates/images/', url_relative_path='templates/images/', ) }), ), column_formatters = {'image_name': _logo_list_thumbnail} def is_accessible(self): return session.get('user') == admin_emai def inaccessible_callback(self, name, **kwargs): if not self.is_accessible(): return redirect(url_for('index', next=request.url)) form_extra_fields = { 'image_name': form.ImageUploadField( 'Image', base_path='templates/images/', url_relative_path='templates/images/', ) }
class MultiImage(AdminView): """Overriding the custom view and adding file upload forms , since the admin would need an ability to add new products to his web site , i didnt find enough material on this topic so i created 3 individual fields , i guess this will require changes in future.""" def _list_thumbnail(view, context, model, name): if not model.filename: return '' elif not model.filename_two: return '' elif not model.filename_tree: return '' return Markup( '<img src="{model.url}" style="width: 150px;"><img src="{model.url_two}" style="width: 150px;"><img src="{model.url_tree}" style="width: 150px;">'.format(model=model) ) form_extra_fields = { 'filename': form.ImageUploadField( 'image', base_path = image_path, url_relative_path = 'app/static/images', ), 'filename_two': form.ImageUploadField( 'image_two', base_path = image_path, url_relative_path = 'app/static/images', ), 'filename_tree': form.ImageUploadField( 'image_tree', base_path = image_path, url_relative_path = 'app/static/images', ), } column_list = [ 'image', 'name', 'filename', 'price', ] column_formatters = { 'image': _list_thumbnail } @event.listens_for(Article, 'after_delete') def del_image(mapper, connection, target): if target.filename is not None: try: os.remove(op.join(image_path, target.filename)) os.remove(op.join(image_path, target.filename_two)) os.remove(op.join(image_path, target.filename_tree)) except OSError or TypeError: pass
class ArticleView(ModelView): form_extra_fields={'cover':form.ImageUploadField('Article Picture', base_path=flaskapp.config['UPLOAD_FOLDER']), 'img_detail_1':form.ImageUploadField('Image Detail 1', base_path=flaskapp.config['UPLOAD_FOLDER']), 'img_detail_2':form.ImageUploadField('Image Detail 2', base_path=flaskapp.config['UPLOAD_FOLDER']), 'img_detail_3':form.ImageUploadField('Image Detail 3', base_path=flaskapp.config['UPLOAD_FOLDER'])} def on_model_change(self, form, model, is_created=True): filename = secure_filename(form.cover.data.filename) model.cover = filename
class CategoryView(ModelView): form_excluded_columns = ['created_at', 'modified_at'] column_display_all_relations = True def _list_thumbnail(view, context, model, name): if not model.path: return '' return Markup('<img src="%s">' % url_for('static', filename=form.thumbgen_filename(model.path))) inline_models = [(Image, dict( form_excluded_columns = ['created_at', 'modified_at'], column_formatters = {'path': _list_thumbnail}, form_extra_fields = { 'path': form.ImageUploadField('Path', base_path=product_path, thumbnail_size=(250, 250, True), url_relative_path='img/product_images') } ) ) ] column_formatters = { 'path': _list_thumbnail } form_excluded_columns = ['created_at', 'modified_at'] column_exclude_list = ('created_at', 'modified_at')
class ProductView(ModelView): can_view_details = True column_list = ('image', 'name', 'description', 'price', 'active') column_editable_list = ('name', 'description', 'price', 'active') def is_accessible(self): return current_user.is_authenticated and current_user.has_role('admin') def _handle_view(self, name, **kwargs): if not self.is_accessible(): if current_user.is_authenticated: abort(403) else: return redirect(url_for('security.login', next=request.url)) column_formatters = { 'image': product_image_formatter } form_extra_fields = { 'image': form.ImageUploadField( 'Image', base_path=imagedir, url_relative_path='images/', thumbnail_size=(200, 200, True), namegen=secure_uuid_filename) } can_export = True
class GoodView(ModelView): column_list=('id','title', 'price', 'quantity', 'imgsrc') column_searchable_list = ['title'] def _list_thumbnail(view, context, model, title): if not model.imgsrc: return '' return Markup('<img src="{}">'.format(url_for( 'static', filename=form.thumbgen_filename('images/' + model.imgsrc)))) form_columns = ['title', 'desc', 'price', 'quantity', 'imgsrc', 'category'] column_formatters = { 'imgsrc': _list_thumbnail } form_extra_fields = { 'imgsrc': form.ImageUploadField('Image', base_path=img_path, url_relative_path='images/', thumbnail_size=(100, 100, True), allowed_extensions=['jpg','png','jpeg'], ) }
class AuthorView(ModelView): form_extra_fields={'photo':form.ImageUploadField('Profile Picture', base_path=flaskapp.config['UPLOAD_FOLDER'])} def on_model_change(self, form, model, is_created=True): filename = secure_filename(form.photo.data.filename) model.photo = filename
class FModelview(MyModelView): column_labels = { 'id': '序号', 'summary': '描述', 'stock': '库存量', 'category': '分类', } def get_img(view, context, model, name): if not model.main_image: return '' return Markup('<img src="%s">' % url_for('static', filename=model.main_image)) column_formatters = {'main_image': get_img} # Alternative way to contribute field is to override it completely. # In this case, Flask-Admin won't attempt to merge various parameters for the field. form_extra_fields = { 'main_image': form.ImageUploadField('Image', base_path=file_path, relative_path="uploadfile/") }
class Products_View(MyModelView): olumn_display_pk = False can_create = True can_delete = True can_export = True column_list = ('Images', 'Name', 'Price', 'category') form_columns = ('Name', 'Price', 'Description', 'Images', 'category') column_labels = { 'Game_ID': 'Game ID', 'Name': 'Title', 'Price': 'Price', 'Description': 'Description', 'Images': 'Image', 'Type_ID': 'Category ID', 'category': 'Category' } column_formatters = {'Images': render_image} form_extra_fields = { 'Images': form.ImageUploadField('Image', base_path=file_path) } form_overrides = {'Description': CKTextAreaField} page_size = 10 create_template = 'Admin/addnew.html' edit_template = 'Admin/update.html'
class UModelview(MyModelView): column_labels = { 'id': '序号', 'email': '邮件', 'username': '******', 'role': '角色', 'password_hash': '密码', 'head_img': '头像', 'create_time': '创建时间', 'update_time': '更新时间' } column_exclude_list = [ 'password_hash', ] def _list_thumbnail(view, context, model, name): if not model.head_img: return '' return Markup( '<img src="%s">' % url_for('static', filename=form.thumbgen_filename(model.head_img))) column_formatters = {'head_img': _list_thumbnail} # Alternative way to contribute field is to override it completely. # In this case, Flask-Admin won't attempt to merge various parameters for the field. form_extra_fields = { 'head_img': form.ImageUploadField('Image', base_path=file_path, relative_path="uploadfile/", thumbnail_size=(100, 100, True)) }
class ImageView(ModelView): def _list_thumbnail(view, context, model, name): if not model.path: return '' return Markup( '<img src="%s">' % url_for('static', filename=form.thumbgen_filename(model.path))) #column_formatters = { #'path': _list_thumbnail #} #form_columns = ('name', 'Image', 'Url') column_searchable_list = ('name', ) column_exclude_list = ('path', 'Path') edit_modal = True create_modal = True # Alternative way to contribute field is to override it completely. # In this case, Flask-Admin won't attempt to merge various parameters for the field. form_extra_fields = { 'path': form.ImageUploadField('path', base_path='static/images', thumbnail_size=(100, 100, True)) } """
class ImageView(BaseView): form_excluded_columns = ('inventory', ) def _list_thumbnail(view, context, model, name): if not model.path: return '' return Markup('<img src="{}">'.format( url_for('static', filename='img/' + form.thumbgen_filename(model.path)))) column_formatters = {'path': _list_thumbnail} form_extra_fields = { 'file_path': StringField('Directory', default=file_path, render_kw={'readonly': True}), 'path': form.ImageUploadField('Image', base_path=file_path, url_relative_path='img/', thumbnail_size=(100, 100, True)) }
class AdminVenueView(ModelView): column_labels = { 'address1': 'Address', 'address2': 'Address 2', 'web_url': 'Website' } column_default_sort = 'name' column_exclude_list = ('description') form_columns = ('name', 'address1', 'address2', 'city', 'state', 'postal_code', 'description', 'web_url', 'phone_number', 'venue_photo') form_excluded_columns = ['films'] form_overrides = {'description': TextAreaField} form_widget_args = { 'address1': { 'placeholder': 'Primary address' }, 'address2': { 'placeholder': 'Suite/Bulding/Other' }, 'description': { 'rows': 5, 'style': 'color: black', 'maxlength': 1000, 'placeholder': 'max 1000 characters', 'spellcheck': 'true' }, 'phone_number': { 'placeholder': '123.456.7890' } } form_extra_fields = { 'venue_photo': form.ImageUploadField( 'Venue Photo', base_path='reel_miami/static/img/venues', url_relative_path='img/venues/', ), 'state': SelectField(label='State', choices=[('FL', 'Florida')], default='FL') } def is_accessible(self): return (current_user.is_active and current_user.is_authenticated and (current_user.has_role('Superuser') or current_user.has_role('User'))) def _handle_view(self, name, **kwargs): """ Override builtin _handle_view in order to redirect users when a view is not accessible. """ if not self.is_accessible(): if current_user.is_authenticated: # permission denied abort(403) else: # login return redirect(url_for('security.login', next=request.url))
class ImageView(BaseModelView): def _list_thumbnail(view, context, model, name): if not model.path: return '' return Markup('<img src="%s">' % url_for( 'images', filename='blog/' + form.thumbgen_filename(model.path))) column_formatters = {'path': _list_thumbnail} form_excluded_columns = ['url'] form_extra_fields = { 'path': form.ImageUploadField('Image', base_path=file_path, namegen=prefix_name, thumbnail_size=(100, 100, True)) } def after_model_change(self, form, model, is_created): model.url = request.host_url + 'images/blog/' + model.path db.session.commit() def after_model_delete(self, model): if model.path: try: os.remove(op.join(file_path, model.path)) except OSError: pass try: os.remove( op.join(file_path, form.thumbgen_filename(model.path))) except OSError: pass
class MyPostView(MyModelView): form_overrides = dict(body=CKTextAreaField) def _list_thumbnail(view, context, model, name): if not model.path: return '' return Markup('<img src="%s" height="180px">' % url_for( 'static', filename='files/' + form.thumbgen_filename(model.path))) def _body_slice(view, context, model, name): return model.body[:10] def _preview_slice(view, context, model, name): return model.previewtext[:10] column_formatters = { 'path': _list_thumbnail, 'body': _body_slice, 'previewtext': _preview_slice } form_extra_fields = { 'path': form.ImageUploadField('Image', base_path=file_path, endpoint='static', thumbnail_size=(360, 240, True)) }
class ProductsView(CustomModelView): column_searchable_list = ('title', 'price') column_list = ('title', 'descr', 'price', 'image') column_filters = ('date', 'title', 'price') form_excluded_columns = ('public_id', 'products', 'rates', 'comments', 'slug', 'date') form_extra_fields = {"image": FileField('image')} def on_model_change(self, form, model, is_created): image_path = os.path.join(current_app.root_path, 'static', 'images', 'products') # file = request.files['image'] file = request.files.get(form.image.name) if file.filename == '': original_image = model.image if file and allowed_file(file.filename): filename = secure_filename(file.filename) model.image = '/static/images/thumbs/' + filename file.save(os.path.join(image_path, filename)) model.slug = base_slugify(model.title) db.session.commit() def _list_thumbnail(view, context, model, name): if not model.image: return '' if model.image: return Markup('<img src="{image}" style="width:100px;">'.format( image=model.image)) return Markup('<img src="%s">' % url_for( 'static', filename='images/thumbs/' + form.thumbgen_filename(model.image))) form_overrides = {'image': form.FileUploadField} form_args = { 'image': { 'label': 'Product', 'base_path': file_path, 'allow_overwrite': False } } column_formatters = {'image': _list_thumbnail} form_extra_fields = { 'image': form.ImageUploadField('Image', base_path=file_path, thumbnail_size=(100, 100, True)) }
class ViewIkan(UserAkses): form_overrides = dict(keterangan_ikan=CKEditorField) column_list = ('id_ikan', 'nama_ikan', 'keterangan_ikan', 'berat_ikan_dalam_Kg', 'minimal_order_dalam_Kg', 'harga_per_Kg', 'foto_ikan') create_template = 'admin/ckeditor.html' edit_template = 'admin/ckeditor.html' def _list_thumbnail(view, context, model, name): if not model.foto_ikan: return '' return Markup('<img src="%s">' % url_for( 'static', filename=form.thumbgen_filename(model.foto_ikan))) column_formatters = {'foto_ikan': _list_thumbnail} # Alternative way to contribute field is to override it completely. # In this case, Flask-Admin won't attempt to merge various parameters for the field. form_extra_fields = { 'foto_ikan': form.ImageUploadField('Foto Ikan', base_path=file_path, thumbnail_size=(100, 100, True)) }
class BodyPartsView(BaseView): allowed_extensions = ('jpeg', 'gif', 'png') column_labels = dict(image_name='Image') form_create_rules = ('name', 'image_name', 'subparts', 'active') form_edit_rules = ('name', 'image_name', 'subparts', 'active') column_searchable_list = ('name', ) def _imagename_uuid1_gen(obj, file_data): _, ext = os.path.splitext(file_data.filename) uid = uuid.uuid1() return secure_filename('{}{}'.format(uid, ext)) form_extra_fields = { 'image_name': form.ImageUploadField('Image', base_path=app.config['KNEED_HELP_IMAGES_DIR'], namegen=_imagename_uuid1_gen) } def _list_thumbnail(view, context, model, name): if not model.image_name: return '' return Markup('<img height="57" width="57" src="%s">' % (url_for('.viewImage', image_name=model.image_name))) column_formatters = {'image_name': _list_thumbnail} @expose('/viewImage/<string:image_name>') def viewImage(self, image_name): try: return send_from_directory( current_app.config['KNEED_HELP_IMAGES_DIR'], image_name) except BadRequest: return abort('Filename not found.')
class MyArticleView(ModelView): column_list = ('title', 'date', 'anons') form_overrides = dict(text=CKEditorField) create_template = 'edit.html' edit_template = 'edit.html' img_dir = base_config.UPLOADED_PATH + "/article" try: os.mkdir(img_dir) except: ... def prefix_name(obj, file_data): parts = os.path.splitext(file_data.filename) rand_string = ''.join( random.choice('qwertyuiopasdfghjklzxcvbnm1234567890') for _ in range(random.randint(15, 40))) return secure_filename(rand_string + '_file-%s%s' % parts) form_extra_fields = { 'image': admin_form.ImageUploadField('Image', base_path=img_dir, endpoint="uploads", namegen=prefix_name, url_relative_path="article/", thumbnail_size=(100, 80, True)) } def is_accessible(self): return login.current_user.is_authenticated
class Secretadmin(BaseModelview): extra_js = ['//cdn.ckeditor.com/4.6.0/standard/ckeditor.js'] form_overrides = { 'secret_content': CKTextAreaField } # 设置缩略图的 def _list_thumbnail(view, context, model, name): if not model.secret_img: return '' return Markup('<img src="%s">' % url_for('static', filename=form.thumbgen_filename(model.secret_img))) # 格式化列表的图像显示 column_formatters = { 'secret_img': _list_thumbnail } form_extra_fields = { 'secret_img': form.ImageUploadField('secret_img', base_path=file_path, relative_path='images/secretimgs/', thumbnail_size=(215, 111, True)) }
class UserModelView(ModelView): can_create = False can_delete = False def _list_thumbnail(view, context, model, name): if not model.img: return '' return Markup('<img src="%s">' % url_for('static', filename=form.thumbgen_filename(model.img))) column_formatters = { 'img': _list_thumbnail } form_extra_fields = { 'img': form.ImageUploadField('图片', base_path=file_path, relative_path='uploadFile/', thumbnail_size=(100, 100, True)) } column_labels = { 'id': '序号', 'username': '******', 'name': '姓名', 'is_super_user': '******', 'sex': '性别', 'img': '头像', 'is_delete': '是否删除', 'album_of_user': '******', } column_list = ('id', 'username', 'name', 'sex', 'img', 'is_super_user') def __init__(self, session, **kwargs): super(UserModelView, self).__init__(User, session, **kwargs)
class SodasettingAdmin(sqla.ModelView): #column_display_pk = True can_create = False #can_delete = False #can_edit = False form_excluded_columns = ('sod_id') column_labels = dict(mixset='Soda', sod_pins="Soda Pins", sod_datetime='Datetime of update', sod_price='Price', sod_logo='Logo') # form_columns = ['mixset','sod_pins', 'sod_datetime'] column_exclude_list = ('sod_pins') def is_accessible(self): return login.current_user.is_authenticated def _list_thumbnail(view, context, model, sod_logo): if not model.sod_logo: return '' return Markup('<img src="%s">' % url_for( 'static', filename=form2.thumbgen_filename(model.sod_logo))) column_formatters = {'sod_logo': _list_thumbnail} # Alternative way to contribute field is to override it completely. # In this case, Flask-Admin won't attempt to merge various parameters for the field. form_extra_fields = { 'sod_logo': form2.ImageUploadField('Product logo', base_path=file_path, thumbnail_size=(100, 100, True)) }
class MixtAdmin(sqla.ModelView): #column_display_pk = True can_create = False can_delete = False form_excluded_columns = ('mix_id') column_labels = dict(mix_name='Product Name', mix_desc='Description', mix_logo='Logo', productstatus="Status", mix_datetime="Date updated") form_columns = [ 'mix_name', 'mix_name', 'mix_desc', 'mix_logo', 'productstatus', 'mix_datetime' ] def _list_thumbnail(view, context, model, mix_logo): if not model.mix_logo: return '' return Markup('<img src="%s">' % url_for( 'static', filename=form2.thumbgen_filename(model.mix_logo))) column_formatters = {'mix_logo': _list_thumbnail} # Alternative way to contribute field is to override it completely. # In this case, Flask-Admin won't attempt to merge various parameters for the field. form_extra_fields = { 'mix_logo': form2.ImageUploadField('Product logo', base_path=file_path, thumbnail_size=(100, 100, True)) } def is_accessible(self): return login.current_user.is_authenticated
class ImageView(sqla.ModelView): def _list_thumbnail(view, context, model, name): if not model.path: return '' return Markup('<img src="%s">' % url_for('static', filename='files/'+form.thumbgen_filename(model.path))) def thumb_name(filename): name, _ = op.splitext(filename) return '%s-thumb123.jpg' % name column_formatters = { 'path':_list_thumbnail, #'path':thumb_name } # Alternative way to contribute field is to override it completely. # In this case, Flask-Admin won't attempt to merge various parameters for the field. form_extra_fields = { 'path': form.ImageUploadField('Image', base_path=file_path, thumbnail_size=(100, 100, True), endpoint='static', url_relative_path='files/') #,thumbgen=thumb_name) }
class PhotoModelView(ModelView): def _list_thumbnail(view, context, model, name): if not model.img: return '' return Markup('<img src="%s">' % url_for('static', filename=form.thumbgen_filename(model.img))) column_formatters = { 'img': _list_thumbnail } form_extra_fields = { 'img': form.ImageUploadField('图片', base_path=file_path, relative_path='uploadFile/', thumbnail_size=(100, 100, True)) } column_labels = { 'id': '序号', 'img': '图片', 'img_url': '图片地址', 'content': '详情', 'album_id': '相册', 'label_name': '标签', 'created_time': '上传时间', 'album': '相册', 'album.title': '相册', 'label': '标签', 'is_delete': '是否删除', } column_list = ('id', 'img', 'content', 'album.title', 'label_name', 'created_time') def __init__(self, session, **kwargs): super(PhotoModelView, self).__init__(Photo, session, **kwargs)
class PictureView(BaseBlogView): column_list = [ 'id', 'name', 'state', 'abstract', 'create_time', 'articles', 'location', 'weather', 'user', 'path' ] column_editable_list = ['state', 'location', 'weather'] column_labels = { 'id': u'序号', 'name': u'名字', 'state': u'状态', 'abstract': u'介绍', 'create_time': u'创建时间', 'articles': u'所关联文章', 'user': u'作者', 'location': u'位置', 'weather': u'天气', 'path': u'缩略图' } column_default_sort = ('id', True) # 覆盖path默认显示 def _list_thumbnail(view, context, model, name): try: if not model.path: return '' return Markup('<img src="%s">' % url_for( 'static', filename='blog/picture/' + 'thumb-' + model.path)) except Exception as e: current_app.logger.error(e) column_formatters = {'path': _list_thumbnail} # 处理上传图片名称 def prefix_name(obj, file_data): parts = os.path.splitext(file_data.filename) return str( date.today()) + '-' + random_str() + '-' + parts[0] + parts[1] #return secure_filename('file-%s%s' % (parts[0].encode('utf-8'), parts[1])) # 处理上传图片缩略图名称 def thumb_name(filename): return 'thumb-' + filename # Alternative way to contribute field is to override it completely. # In this case, Flask-Admin won't attempt to merge various parameters for the field. form_extra_fields = { 'path': form.ImageUploadField('Image', base_path=os.path.join(bpdir, 'static/blog/picture'), thumbnail_size=(100, 100, True), max_size=(720, 480, True), namegen=prefix_name, thumbgen=thumb_name) } def __init__(self, session, **kwargs): super(PictureView, self).__init__(Picture, session, **kwargs)
class PostModelView(CustomModelView): form_extra_fields = { 'image_path': form.ImageUploadField('image_path', base_path='app/static/', namegen=prefix_name) } extra_js = ['//cdn.ckeditor.com/4.6.0/standard/ckeditor.js'] form_overrides = { 'body': CKTextAreaField }
class UserView(CustomModelView): column_list = ('username', 'roles', 'confirmed', 'is_admin', 'joined', 'image') column_searchable_list = ('username', 'id') column_filters = ('joined', 'email', 'username') path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) def on_model_change(self, form, model, is_created): path = os.path.abspath( os.path.join(os.path.dirname(__file__), os.pardir)) image_path = os.path.join(current_app.root_path, 'static', 'images') photo_data = request.files.get(form.image.name) if photo_data: name = secure_filename(photo_data.filename) model.image = '/static/images/thumbs/' + name photo_data.save(os.path.join(image_path, name)) def _list_thumbnail(view, context, model, name): if model.image: return Markup('<img src="{avatar}" style="width:100px;">'.format( avatar=model.image)) if not model.image: return Markup('<img src="{avatar}" style="width:100px;">'.format( avatar=model.avatar(100))) return Markup('<img src="%s" style="width:100px;">' % url_for( 'static', filename='images/thumbs/' + form.thumbgen_filename(model.image))) # Override form field to use Flask-Admin FileUploadField form_overrides = {'image': form.FileUploadField} # Pass additional parameters to 'image' to FileUploadField constructor form_args = { 'image': { 'label': 'User', 'base_path': file_path, 'allow_overwrite': False } } column_formatters = {'image': _list_thumbnail} # Alternative way to contribute field is to override it completely. # In this case, Flask-Admin won't attempt to merge various parameters for the field. form_extra_fields = { 'image': form.ImageUploadField('User', base_path=file_path, thumbnail_size=(100, 100, True)) }
class ImageModelView(EnhancedModelView): column_list = ('name', 'path') form_rules = column_details_list = ('name', 'path') form_edit_rules = ('name', 'path') form_extra_fields = { 'path': form.ImageUploadField('Image', IMAGES_DIR, thumbnail_size=(100, 100, True)), }
class ImageView(AdminModelView): form_extra_fields = { "filename": form.ImageUploadField( "Image", base_path=config("UPLOADED_IMAGES_DEST"), url_relative_path="images/", namegen=_imagename_uuid1_gen, ) }