Ejemplo n.º 1
0
class UserModelView(MyBaseModelView):
    # def on_model_change(self, form, User, is_created=False):
    #     # 调用用户模型中定义的set方法
    #     User.set_password(form.password_hash.data)

    # column_exclude_list = ['password_hash', ]
    # column_editable_list = ['password_hash', ]
    form_excluded_columns = [
        'messages',
        'comments',
        'favorites',
        'password_hash',
    ]
    from .models import User
    column_choices = {
        'gender': User.GENDER,
    }

    form_overrides = dict(gender=Select2Field, )
    form_args = dict(gender=dict(coerce=str, choices=User.GENDER), )

    form_extra_fields = {
        'image':
        ImageUploadField('Image',
                         base_path=file_path,
                         relative_path='media/uploadFile/user/',
                         thumbnail_size=(60, 60, True)),
    }

    column_labels = {
        'password_hash': 'password',
    }
Ejemplo n.º 2
0
class ImageView(ModelView):
    def _list_thumbnail(view, context, model, name):
        if not model.path:
            return ''

        prefix = 'img/uploads/'
        return Markup(
            '<img src="%s">' %
            url_for('static', filename=thumbgen_filename(prefix + model.path)))

    column_formatters = {'path': _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 = {
        'path':
        ImageUploadField('Image',
                         base_path=file_path,
                         thumbnail_size=(100, 100, True))
    }

    def __init__(self, dbsession):
        super(ImageView, self).__init__(Image,
                                        dbsession,
                                        name="Image",
                                        category='CMS')
Ejemplo n.º 3
0
class BannerModelView(MyBaseModelView):
    form_extra_fields = {
        'image':
        ImageUploadField('Image',
                         base_path=file_path,
                         relative_path='media/uploadFile/index/',
                         thumbnail_size=(60, 60, True)),
    }
Ejemplo n.º 4
0
class MachineModelView(RoleBasedModelView):
    details_modal = True
    edit_modal = True
    column_exclude_list = ['created_at']
    column_list = [
        Machine.id, Machine.name, Machine.status, 'machine_to_lead_ratio',
        Machine.average_num_workers, 'orders'
    ]
    column_searchable_list = (Machine.id, Machine.name, Machine.status)
    column_labels = dict(average_num_workers='Scheduled Assemblers',
                         machine_to_lead_ratio='Lead to Machine Ratio')

    def _list_thumbnail(view, context, model, name):
        if not model.photo:
            return ''

        return Markup(
            '<img src="%s">' %
            url_for('static', filename=thumbgen_filename(model.photo)))

    def _all_orders(view, context, model, name):
        non_completed_orders = db.session.query(Order).filter(
            and_(Order.assigned_machine_id == model.id,
                 Order.status != 'COMPLETED')).all()
        html = ''
        is_first = True
        for o in non_completed_orders:
            if is_first:
                is_first = False
                html += image_icon_html(o, o.product.num_employee_required)
            else:
                html += image_icon_html(o)

        return Markup(html)

    def _planned_workers(view, context, model, name):
        html = '<i class="glyphicon glyphicon-user">x%s</i>' % str(
            model.average_num_workers)
        return Markup(html)

    column_formatters = {
        'photo': _list_thumbnail,
        'orders': _all_orders,
        'average_num_workers': _planned_workers
    }

    form_extra_fields = {
        'photo':
        ImageUploadField('Image',
                         base_path=file_path,
                         thumbnail_size=(75, 75, True))
    }
    form_columns = ('name', 'status', 'power_in_kilowatt', 'photo',
                    'average_num_workers', 'machine_to_lead_ratio')
    # Sort the data by id in descending order.
    column_default_sort = ('id', True)
    column_filters = ('id', 'name', 'status', 'machine_to_lead_ratio')
Ejemplo n.º 5
0
class ProjectView(ModelView):
    column_list = ('title', 'created', 'updated', 'category')
    form_excluded_columns = ('slug', 'token_edit')
    form_extra_fields = {
        'screenshot':
        ImageUploadField('Screenshot',
                         base_path=screenshot_path,
                         url_relative_path='/screenshots/',
                         thumbnail_size=(256, 256, True))
    }
    inline_models = [Rendering]
    can_export = True

    def on_model_change(view, form, model, is_created):
        model.slug = helper.slugify(form.title.data)
Ejemplo n.º 6
0
class ProjectAdminView(OrderableModelView):
    form_extra_fields = {
        "image_path":
        ImageUploadField(
            label="Image",
            base_path=f"{BackendSettings.DATA_DIR}/project_images",
            endpoint="data",
            relative_path="project_images",
            url_relative_path="",
        ),
        "notebook_path":
        FileUploadField(
            label="Notebook",
            base_path=f"{BackendSettings.DATA_DIR}/project_notebooks",
            relative_path="project_notebooks",
        ),
    }

    form_overrides = {"description": CKTextAreaField}
    column_labels = {"image_path": "Image", "notebook_path": "Notebook"}
    extra_js = ["//cdn.ckeditor.com/4.6.0/standard/ckeditor.js"]
    column_editable_list = ("position", "archived", "role", "year")
    column_formatters = {"image_path": display_image_list}
    column_list = ("image_path", "position", "archived", "name", "role",
                   "year", "short_description")
    inline_models = (models.PortfolioLink, )

    @staticmethod
    def change_file_path_url(form_field, file):
        return f"{form_field.relative_path}/{file.filename}"

    def on_model_change(self, form, model, is_created):
        if hasattr(form, "image_path") or hasattr(form, "notebook_path"):
            image_file = form.image_path.data
            notebook_file = form.notebook_path.data

            try:
                model.image_path = self.change_file_path_url(
                    form.image_path, image_file)
            except AttributeError:
                print("Updating without new image")
            try:
                model.notebook_path = self.change_file_path_url(
                    form.notebook_path, notebook_file)
            except AttributeError:
                print("Updating without new notebook")
        super().on_model_change(form, model, is_created)
Ejemplo n.º 7
0
class TeacherModelView(MyBaseModelView):
    form_excluded_columns = [
        'courses',
    ]

    column_choices = {
        'profession': Teacher.PROFESSIONAL,
    }
    form_overrides = dict(profession=Select2Field, )
    form_args = dict(profession=dict(coerce=str,
                                     choices=Teacher.PROFESSIONAL), )
    form_extra_fields = {
        'image':
        ImageUploadField('Image',
                         base_path=file_path,
                         relative_path='media/uploadFile/teacher/',
                         thumbnail_size=(60, 60, True)),
    }
Ejemplo n.º 8
0
class CourseOrgModelView(MyBaseModelView):
    form_excluded_columns = ['courses', 'teachers']
    column_choices = {
        'category': CourseOrg.ORG_CATEGORY,
    }
    form_overrides = dict(
        category=Select2Field,
        detail=UEditorField,
    )
    form_args = dict(category=dict(coerce=str,
                                   choices=CourseOrg.ORG_CATEGORY), )
    form_extra_fields = {
        'image':
        ImageUploadField('Image',
                         base_path=file_path,
                         relative_path='media/uploadFile/org/',
                         thumbnail_size=(60, 60, True)),
    }
Ejemplo n.º 9
0
class CourseModelView(MyBaseModelView):
    column_choices = {
        'degree': Course.COURSE_GRADE,
    }

    form_excluded_columns = ['lessons', 'users']
    form_overrides = dict(
        degree=Select2Field,
        detail=UEditorField,
    )
    form_args = dict(degree=dict(coerce=str, choices=Course.COURSE_GRADE), )
    column_filters = ('add_time', 'name', 'click_nums')
    form_extra_fields = {
        'image':
        ImageUploadField('Image',
                         base_path=file_path,
                         relative_path='media/uploadFile/course/',
                         thumbnail_size=(60, 60, True)),
    }
Ejemplo n.º 10
0
class PersonView(ModelView):
    column_list = ('first_name', 'last_name', 'affiliation')
    form_choices = {
        'select_career_stage': [(d.name, d.value) for d in CareerStage],
        'resource_type': [(d.name, d.value) for d in ResourceType],
    }
    form_extra_fields = {
        'upload_photo':
        ImageUploadField('Photo',
                         base_path=Config.UPLOAD_DIR,
                         relative_path='photos/',
                         endpoint='client_app.index_uploads',
                         thumbnail_size=(256, 256, True))
    }
    inline_models = [Organisation, Expertise, Project, Resource]

    def on_model_change(self, form, model, is_created):
        print("Reindexing on save")
        from .loader.util import reindex_data
        reindex_data(db, Person, model)
Ejemplo n.º 11
0
class WebSiteInfoModelView(ModelView):
    form_extra_fields = {
        "avatar_image_path":
        ImageUploadField(
            label="image",
            base_path=f"{BackendSettings.DATA_DIR}",
            endpoint="data",
            relative_path="",
            url_relative_path="",
        )
    }

    @expose("/")
    def index_view(self):
        qs = models.WebSiteInfo.query.all()
        if qs:
            obj = qs[0]
            return redirect(
                f"/admin/websiteinfo/edit/?id={obj.id}&url=%2Fadmin%2Fwebsiteinfo%2F"
            )
        else:
            return redirect(
                "/admin/websiteinfo/new/?url=%2Fadmin%2Fwebsiteinfo%2F")
Ejemplo n.º 12
0
 def __init__(self, *args , ** kwargs):
     ImageUploadField.__init__(self, base_path=current_app.config['UPLOADED_PHOTOS_DEST'],
                               endpoint ='bp_upload.getimg', **kwargs)
Ejemplo n.º 13
0
class MyForm(BaseForm):
    upload = ImageUploadField('File', thumbgen=path)
Ejemplo n.º 14
0
class ProductModelView(RoleBasedModelView):
    details_modal = True
    edit_modal = False
    column_exclude_list = ['created_at', 'updated_at']
    # Rename 'title' columns to 'Post Title' in list view
    column_list = (Product.id, Product.name, Product.photo, 'colors', 'weight',
                   Product.time_to_build, Product.num_employee_required,
                   'machine', Product.raw_material_weight_per_bag,
                   Product.multi_colors_ratio)
    # List column renaming
    column_labels = dict(
        selling_price='Price',
        num_employee_required='Employee Required',
        machine='Default Machine',
        weight='Weight (Lb)',
        time_to_build='Time To Build (sec)',
        raw_material_weight_per_bag='Raw Material Weight Per Bag')

    def _colors(view, context, model, name):
        html = color_boxes_html(model.colors)
        return Markup(html)

    def _list_thumbnail(view, context, model, name):
        if not model.photo:
            return ''

        return Markup(
            '<img src="%s">' %
            url_for('static', filename=thumbgen_filename(model.photo)))

    column_formatters = {'photo': _list_thumbnail, 'colors': _colors}

    form_columns = (
        'name',
        'photo',
        'colors',
        'multi_colors_ratio',
        'machine',
        'weight',
        'time_to_build',
        'selling_price',
        'num_employee_required',
        'raw_material_weight_per_bag',
    )

    form_ajax_refs = {
        'colors': {
            'fields': (Color.name, )
        },
        'machine': {
            'fields': (
                Machine.id,
                Machine.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 = {
        'photo':
        ImageUploadField('Image',
                         base_path=file_path,
                         thumbnail_size=(75, 75, True))
    }
    # Create form fields adjustment.
    # Sort the data by id in descending order.
    column_default_sort = ('id', True)
    column_filters = ('id', 'name', 'weight', 'time_to_build',
                      'num_employee_required', 'machine.name',
                      'raw_material_weight_per_bag')
Ejemplo n.º 15
0
class UserModelView(RoleBasedModelView):
    details_modal = True
    edit_modal = True
    column_list = [
        'photo', User.id, User.name, User.gender, User.is_in, 'shift', 'roles',
        User.active, User.email
    ]
    form_columns = (User.name, User.gender, User.email, User.password, 'roles',
                    'shift', User.phone, User.active, User.is_in, 'photo')

    def _list_thumbnail(view, context, model, name):
        if not model.photo:
            return ''

        return Markup(
            '<img src="%s">' %
            url_for('static', filename=thumbgen_filename(model.photo)))

    column_formatters = {'photo': _list_thumbnail}

    form_extra_fields = {
        'photo':
        ImageUploadField('Image',
                         base_path=file_path,
                         thumbnail_size=(75, 75, True))
    }
    # Sort the data by id in descending order.
    column_default_sort = ('id', True)
    column_sortable_list = ['id', 'name', 'email', 'active', 'is_in', 'gender']
    column_filters = ('id', 'name', 'gender', 'is_in', 'active', 'email',
                      'shift.name', 'roles.name')

    @action('enable', 'Enable',
            'Are you sure you want to enable selected users?')
    def action_enable(self, ids):
        self.toggle_user_status(ids, True)

    @action('disable', 'Disable',
            'Are you sure you want to disable selected users?')
    def action_disable(self, ids):
        self.toggle_user_status(ids, False)

    def toggle_user_status(self, ids, flag=False):
        try:
            query = User.query.filter(User.id.in_(ids))
            count = 0
            for user in query.all():
                if user.active != flag:
                    user.active = flag
                    count += 1

            if count > 0:
                self.session.commit()

            flash(
                ngettext('User was successfully disabled',
                         '%(count)s users were successfully disabled',
                         count,
                         count=count))
        except Exception as ex:
            if not self.handle_view_exception(ex):
                raise

            flash(
                gettext('Failed to update user status. %(error)s',
                        error=str(ex)), 'error')