Exemplo n.º 1
0
class t_work_battledore_admin(object):
    search_box_flag = True
    show_prompt_develop = True
    downloadxls = True

    progress_tracking_plugin = True

    def show_Image(self, obj):
        url = u'%s' % (obj.image)
        rt = '<img src="%s" width="150" height="150" alt = "%s" title="%s">' \
             '</img>'%(url,url,url)
        return mark_safe(rt)

    show_Image.short_description = u'图片'

    def show_Link(self, obj):
        rt = u'反向链接:<a title="%s" href="%s" target="_blank">%s...</a>' % (
            obj.urllink, self.del_None(obj.urllink), self.del_None(
                obj.urllink)[:20])
        rt = u'%s</br>1688链接:<a title="%s" href="%s" target="_blank">%s...</a>' % (
            rt, obj.linkali, self.del_None(
                obj.linkali), self.del_None(obj.linkali)[:20])
        return mark_safe(rt)

    show_Link.short_description = u'链接'

    def show_time(self, obj):
        rt = u'需求提交时间:%s' % obj.submittime

        if obj.proflag == '1':
            rt = u'%s</br><span style="color:red">确定面辅料完成时间:%s</span>' % (
                rt, obj.determinetime)
        else:
            rt = u'%s</br>确定面辅料完成时间:%s' % (rt, obj.determinetime)
        if obj.proflag == '2':
            rt = u'%s</br><span style="color:red">纸样样衣完成时间:%s</span>' % (
                rt, obj.patterntime)
        else:
            rt = u'%s</br>纸样样衣完成时间:%s' % (rt, obj.patterntime)
        if obj.proflag == '3':
            rt = u'%s</br><span style="color:red">审核样衣完成时间:%s</span>' % (
                rt, obj.examinetime)
        else:
            rt = u'%s</br>审核样衣完成时间:%s' % (rt, obj.examinetime)
        if obj.proflag == '4':
            rt = u'%s</br><span style="color:red">报价完成时间:%s</span>' % (
                rt, obj.checktime)
        else:
            rt = u'%s</br>报价完成时间:%s' % (rt, obj.checktime)
        # if obj.proflag == '5':
        #     rt = u'%s</br><span style="color:red">跟单领取时间:%s</span>' % (rt, obj.documentarytime)
        # else:
        #     rt = u'%s</br>跟单领取时间:%s' % (rt, obj.documentarytime)
        return mark_safe(rt)

    show_time.short_description = u'操作时间信息'

    def show_warning(self, obj):
        rt = u'<div style="background:green;color:white">正在进行中</div>'
        if obj.proflag == '1' and (
                obj.submittime + timedelta(days=2)
        ).strftime('%Y-%m-%d') < datetime.now().strftime('%Y-%m-%d'):
            rt = u'<div style="background:red;color:white">确定面辅料-超时</div>'
        elif obj.proflag == '2' and (
                obj.determinetime + timedelta(days=3)
        ).strftime('%Y-%m-%d') < datetime.now().strftime('%Y-%m-%d'):
            rt = u'<div style="background:red;color:white">纸样样衣-超时</div>'
        elif obj.proflag == '3' and (
                obj.patterntime + timedelta(days=0)
        ).strftime('%Y-%m-%d') < datetime.now().strftime('%Y-%m-%d'):
            rt = u'<div style="background:red;color:white">审核样衣-超时</div>'
        elif obj.proflag == '4' and (
                obj.examinetime + timedelta(days=0)
        ).strftime('%Y-%m-%d') < datetime.now().strftime('%Y-%m-%d'):
            rt = u'<div style="background:red;color:white">报价-超时</div>'
        # elif obj.proflag == '5' and (obj.checktime + timedelta(days=0)).strftime('%Y-%m-%d') < datetime.now().strftime('%Y-%m-%d'):
        #     rt = u'<div style="background:red;color:white">跟单领取-超时</div>'
        elif obj.proflag == '5':
            rt = u'<div style="background:green;color:white">完成</div>'

        return mark_safe(rt)

    show_warning.short_description = u'超时告警'

    def del_None(self, col):
        rt = col
        if not col:
            rt = ''
        return rt

    def show_infors(self, obj):
        read = ''
        if obj.proflag == '5':
            read = 'readonly'
        rt = '<table>'
        rt = u'%s<tr><th>供应链成本:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th> </tr>' \
             u'<tr><th>供应链克重:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr> ' % \
             (rt,self.del_None(obj.price),obj.id,'price',read,self.del_None(obj.price),str(obj.id)+'_price',
              self.del_None(obj.weight),obj.id,'weight',read,self.del_None(obj.weight),str(obj.id)+'_weight',)

        rt = u'%s<tr><th>面料数量:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr> ' % \
             (rt,self.del_None(obj.num),obj.id,'num',read,self.del_None(obj.num),str(obj.id)+'_num')
        rt = u'%s<tr><th>剪版费用:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr> ' % \
             (rt, self.del_None(obj.shearplate), obj.id, 'shearplate', read, self.del_None(obj.shearplate), str(obj.id) + '_shearplate')
        rt = u'%s<tr><th>报价备注:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr> ' % \
             (rt, self.del_None(obj.priceremark), obj.id, 'priceremark', read, self.del_None(obj.priceremark), str(obj.id) + '_priceremark')

        rt = rt + '</table>'

        return mark_safe(rt)

    show_infors.short_description = u'报价信息'

    def show_needsinfors(self, obj):
        read = ''
        if obj.proflag == '5':
            read = 'readonly'
        rt = '<table>'
        rt = u'%s<tr><th>1688成本:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th> </tr>' \
             u'<tr><th>1688克重:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr> ' % \
             (rt,self.del_None(obj.aliprice),obj.id,'aliprice',read,self.del_None(obj.aliprice),str(obj.id)+'_aliprice',
              self.del_None(obj.aliweight),obj.id,'aliweight',read,self.del_None(obj.aliweight),str(obj.id)+'_aliweight')

        rt = u'%s<tr><th>正常售价:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr> ' % \
             (rt,self.del_None(obj.normalprice),obj.id,'normalprice',read,self.del_None(obj.normalprice),str(obj.id)+'_normalprice')

        rt = u'%s<tr><th>需要颜色:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr>' \
             u'<tr><th>卖点或配件:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr>' % \
             (rt,self.del_None(obj.color),obj.id,'color',read,self.del_None(obj.color),str(obj.id)+'_color',
              self.del_None(obj.keynote),obj.id,'keynote',read,self.del_None(obj.keynote),str(obj.id)+'_keynote')

        rt = u'%s<tr><th>需求备注:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr> ' % \
             (rt, self.del_None(obj.subreamrk), obj.id, 'subreamrk', read,self.del_None(obj.subreamrk), str(obj.id) + '_subreamrk')

        rt = u'%s<tr><th>普元尺码号:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr> ' % \
             (rt, self.del_None(obj.pysize), obj.id, 'pysize', read,self.del_None(obj.pysize), str(obj.id) + '_pysize')

        rt = rt + '</table>'

        return mark_safe(rt)

    show_needsinfors.short_description = u'需求信息'

    def show_maninfors(self, obj):
        read = ''
        if obj.proflag == '5':
            read = 'readonly'
        rt = '<table>'
        rt = u'%s<tr><th>采购员:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr> ' % \
             (rt, self.del_None(obj.cgperson), obj.id, 'cgperson', 'readonly', self.del_None(obj.cgperson),str(obj.id) + '_cgperson')

        rt = u'%s<tr><th>需求提交人:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr> ' % \
             (rt, self.del_None(obj.submiter), obj.id, 'submiter', 'readonly', self.del_None(obj.submiter), str(obj.id) + '_submiter')

        rt = u'%s<tr><th>核价员:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th> </tr>' \
             u'<tr><th>纸样师:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr> ' % \
             (rt,self.del_None(obj.checkman),obj.id,'checkman',read,self.del_None(obj.checkman),str(obj.id)+'_checkman',
              self.del_None(obj.patternman),obj.id,'patternman',read,self.del_None(obj.patternman),str(obj.id)+'_patternman')

        # rt = u'%s<tr><th>跟单员:</th><th><input value="%s" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'1\')" %s title="%s"/><span id="%s"></span></th></tr> ' % \
        #      (rt,self.del_None(obj.merchandiser),obj.id,'merchandiser',read,self.del_None(obj.merchandiser),str(obj.id)+'_merchandiser')

        rt = rt + '</table>'

        return mark_safe(rt)

    show_maninfors.short_description = u'人员信息'

    list_display = ('id', 'show_Image', 'mainsku', 'show_needsinfors',
                    'show_infors', 'show_maninfors', 'show_warning',
                    'show_time', 'show_Link')
    # search_fields = ('id','image','keynote','color','mainsku','price','weight','num','submiter','checkman',
    #                  'patternman','examineman','merchandiser','urllink','linkali')
    # list_filter = ('submittime','checktime','patterntime','examinetime','documentarytime')
    list_editable = (
        'keynote',
        'color',
        'price',
        'weight',
        'num',
    )

    fields = ('mainsku', 'urllink', 'keynote', 'color', 'normalprice', 'image')

    form_layout = (Fieldset(u'需求信息填写',
                            Row('urllink', 'normalprice', 'image'),
                            Row('mainsku', 'color', 'keynote'),
                            css_class='unsort '), )

    actions = ['to_check', 'to_pattern', 'to_examine', 'to_offer', 'to_excel']

    def to_check(self, request, objs):
        for obj in objs:
            if obj.proflag == '1':
                obj.determinetime = datetime.now()
                obj.proflag = '2'
                obj.save()

    to_check.short_description = u'确定面辅料完成'

    def to_pattern(self, request, objs):
        for obj in objs:
            if obj.proflag == '2':
                obj.patterntime = datetime.now()
                obj.proflag = '3'
                obj.save()

    to_pattern.short_description = u'纸样样衣完成'

    def to_examine(self, request, objs):
        for obj in objs:
            if obj.proflag == '3':
                obj.examinetime = datetime.now()
                obj.proflag = '4'
                obj.save()

    to_examine.short_description = u'审核样衣完成'

    def to_offer(self, request, objs):
        for obj in objs:
            if obj.proflag == '4':
                obj.checktime = datetime.now()
                obj.proflag = '5'
                obj.save()

    to_offer.short_description = u'报价完成'

    def to_excel(self, request, queryset):
        from xlwt import *

        path = MEDIA_ROOT + 'download_xls/' + request.user.username
        mkdir_p(MEDIA_ROOT + 'download_xls')
        os.popen('chmod 777 %s' % (MEDIA_ROOT + 'download_xls'))

        mkdir_p(path)
        os.popen('chmod 777 %s' % (path))

        w = Workbook()
        sheet = w.add_sheet('sku')

        FIELDS = [
            u'需求提交时间', u'主SKU', u'核价员', u'剪版费用', u'备注', u'正常售价', u'跟单员',
            u'供应链成本', u'供应链克重', u'纸样师', u'纸样样衣完成时间', u'报价完成时间'
        ]

        for index, item in enumerate(FIELDS):
            sheet.write(0, index, item)

        # 写数据
        row = 0

        for qs in queryset:
            row = row + 1
            column = 0
            sheet.write(row, column, u'{}'.format(qs.submittime))  # A 需求提交时间

            column = column + 1
            sheet.write(row, column, u'{}'.format(qs.mainsku))  # B 主SKU

            column = column + 1
            sheet.write(row, column, u'{}'.format(qs.checkman))  # C 核价员

            column = column + 1
            sheet.write(row, column, u'{}'.format(qs.shearplate))  # D 剪版费用

            column = column + 1
            sheet.write(row, column, u'{}'.format(qs.priceremark))  # E 备注

            column = column + 1
            sheet.write(row, column, u'{}'.format(qs.normalprice))  # F 正常售价

            column = column + 1
            sheet.write(row, column, u'{}'.format(qs.merchandiser))  # G 跟单员

            column = column + 1
            sheet.write(row, column, u'{}'.format(qs.aliprice))  # H 供应链成本

            column = column + 1
            sheet.write(row, column, u'{}'.format(qs.aliweight))  # I 供应链克重

            column = column + 1
            sheet.write(row, column, u'{}'.format(qs.patternman))  # J 纸样师

            column = column + 1
            sheet.write(row, column,
                        u'{}'.format(qs.patterntime))  # K 纸样样衣完成时间

            column = column + 1
            sheet.write(row, column, u'{}'.format(qs.checktime))  # L 报价完成时间

        filename = request.user.username + '_' + datetime.now().strftime(
            '%Y%m%d%H%M%S') + '.xls'
        w.save(path + '/' + filename)
        os.popen(r'chmod 777 %s' % (path + '/' + filename))

        # 上传oss对象
        auth = oss2.Auth(ACCESS_KEY_ID, ACCESS_KEY_SECRET)
        bucket = oss2.Bucket(auth, ENDPOINT, BUCKETNAME_XLS)
        bucket.create_bucket(oss2.BUCKET_ACL_PUBLIC_READ)
        # 删除现有的
        for object_info in oss2.ObjectIterator(
                bucket,
                prefix='%s/%s_' %
            (request.user.username, request.user.username)):
            bucket.delete_object(object_info.key)
        bucket.put_object(u'%s/%s' % (request.user.username, filename),
                          open(path + '/' + filename))

        messages.error(
            request, u'%s%s.%s/%s/%s' % (PREFIX, BUCKETNAME_XLS, ENDPOINT_OUT,
                                         request.user.username, filename) +
            u':成功导出,可点击Download下载到本地............................。')

    to_excel.short_description = u'导出EXCEL'

    def save_models(self):
        obj = self.new_obj
        old_obj = None
        if obj is None or obj.id is None or obj.id <= 0:
            pass
        else:
            old_obj = self.model.objects.get(pk=obj.pk)

        try:
            obj.save()

            if obj.mainsku:
                obj.aliprice, obj.aliweight, obj.linkali, obj.pysize, obj.cgperson = get_price_weight_pylink_by_mainsku(
                    obj.mainsku)

            if not obj.linkali:
                linkali_list = t_product_enter_ed.objects.filter(
                    MainSKU=obj.mainsku).values_list('SupplierPUrl1',
                                                     flat=True)
                for linkali in linkali_list:
                    if linkali:
                        obj.linkali = linkali
                        break

            obj.submiter = self.request.user.first_name
            obj.submittime = datetime.now()
            obj.proflag = '1'
            obj.save()
        except Exception, e:
            messages.error(self.request, u'%s:%s' % (Exception, e))
Exemplo n.º 2
0
class t_store_configuration_file_Admin(object):
    store_config_flag = True

    def show_Status(self, obj):

        option = u"<option value ='' selected>未知</option><option value ='0'>正常</option><option value ='-1'>异常</option>"
        if obj.Status == '0':
            option = u"<option value ='0' selected>正常</option>" \
                     u"<option value ='-1'>异常</option>"
        elif obj.Status == '-1':
            option = u"<option value ='0'>正常</option>" \
                     u"<option value ='-1' selected>异常</option>"

        store_status = u"<select class='text-field admintextinputwidget form-control' " \
                       u"onchange='change_status(this,\"%s\")'>" % obj.id \
                      + option + \
                      u"</select>"

        type_show = u"</br><span id='%s'></span>" % obj.id

        return mark_safe(store_status + type_show)
    show_Status.short_description = mark_safe(u'<p align="center"style="color:#428bca;">店铺状态</p>')

    list_display =('id','Department','ShopName','show_Status','Seller','Published','Operators',)
    search_fields = ('id','ShopName','Seller','Published','Operators','ShopType','Submitter',)
    list_filter =('ShopName','Seller','Operators','Published','ShopType','Submitter','Department','Status')
    list_display_links = ('id')
    list_editable = ('ShopName','Seller','Published','Operators','Department','RealName',)


    fields = ('ShopName',
              'Seller',
              'Published',
              'Operators',
              'ShopType',
              'Submitter',
              'Department'
              )
              
    form_layout = (
        Fieldset(u'店铺配置',
                    Row('Department',),
                    Row('ShopName',),
                    Row('Seller',),
                    Row('Published',),
                    Row('Operators',),
                    Row('ShopType',),
                    Row('Submitter',),
                    css_class = 'unsort'
                ),
                  )
 
    def save_models(self):
        obj = self.new_obj
        request = self.request
        old_obj = None
        if obj is None or obj.id is None or obj.id <= 0:
            saveobj = self.model.objects.create(id=None)
            obj.id = saveobj.id
        else:
            old_obj = self.model.objects.get(pk=obj.pk)

        if old_obj is None :
            shopnameobj = self.model.objects.filter(ShopName=obj.ShopName)
            if shopnameobj.exists():
                messages.error(request,u'抱歉!该店铺名已经存在。')
                return
        else:
            pass

        if obj.ShopName is not None and obj.ShopName.strip() != '':
            code = obj.ShopName.strip().split('-')
            if len(code) >= 2:
                obj.ShopName_temp = code[0] + '-' + code[1]
            else:
                obj.ShopName_temp = obj.ShopName.strip()
        else:
            messages.error(request, u'抱歉!请填写店铺名称后保存')
            return

        obj.save()

    def get_list_queryset(self):
        request = self.request
        qs = super(t_store_configuration_file_Admin, self).get_list_queryset()

        seachfilter = {}

        Pstatus = request.GET.get('status')
        if Pstatus:
            PlatformID = Pstatus.split('_')[0]
            if PlatformID:
                seachfilter['PlatformID'] = PlatformID

            sstatus = Pstatus.split('_')[-1]

            if sstatus == 's':
                seachfilter['Status'] = '0'
            elif sstatus == 'e':
                seachfilter['Status'] = '-1'
            elif sstatus == 'o':
                seachfilter['Status__isnull'] = True

        if seachfilter:
            qs = qs.filter(**seachfilter)

        return qs
Exemplo n.º 3
0
class PostAdmin(BaseOwnerAdmin):
    list_display = [
        'title', 'category', 'status',
        'created_time', 'owner', 'operator',
    ]
    list_display_links = []

    list_filter = ['category']
    search_fields = ['title', 'category__name']

    actions_on_top = True
    actions_on_bottom = True

    save_on_top = True

    form = PostAdminForm

    # fields = (
    #     ('category', 'title'),
    #     'desc',
    #     'status',
    #     'content',
    #     'tag',
    # )

    form_layout = (
        Fieldset(
            '基础信息',
            Row("title", "category"),
            'status',
            'tag',
        ),
        Fieldset(
            '内容信息',
            'desc',
            'is_md',
            'content_ck',
            'content_md',
            'content',
        )
    )

    def operator(self, obj):
        return format_html(
            '<a href="{}">编辑</a>',
            # reverse('admin:blog_post_change', args=(obj.id,))
            reverse('xadmin:blog_post_change', args=(obj.id,))
        )

    operator.short_description = '操作'

    # def save_model(self, request, obj, form, change):
    #     obj.owner = request.user
    #     return super(PostAdmin, self).save_model(request, obj, form, change)
    #
    # def get_queryset(self, request):
    #     qs = super(PostAdmin, self).get_queryset(request)
    #     return qs.filter(owner=request.user)

    # class Meta:
    #     css = {
    #         'all': ("https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css",),
    #     }
    #     js = ('https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/js/bootstrap.bundle.js',)


# @xadmin.sites.register(LogEntry)
# class LogEntryAdmin:
#     list_display = ['object_repr', 'object_id', 'action_flag', 'user', 'change_message']
Exemplo n.º 4
0
class DirectorAdmin(RichTextAdmin):
    list_display = ('name_cn', 'name_en', 'intro_cn', 'intro_en')
    form_layout = (Main(Fieldset('头像', 'img'),
                        Fieldset('中文信息', 'name_cn', 'intro_cn', 'detail_cn'),
                        Fieldset('英文信息', 'name_en', 'intro_en', 'detail_en')))
Exemplo n.º 5
0
class BusinessDynamicsAdmin(RichTextAdmin):
    list_display = ('title_cn', 'title_en', 'publish_time')
    form_layout = (Main(Fieldset('图片与日期', 'img', 'publish_time'),
                        Fieldset('中文信息', 'title_cn', 'detail_cn'),
                        Fieldset('英文信息', 'title_en', 'detail_en')))
Exemplo n.º 6
0
class ModuleInfoAdmin(object):
    model = ModuleInfo
    extra = 1
    # 提供1个足够的选项行,也可以提供N个
    style = "accordion"

    # 折叠

    def update_button(self, obj):
        # 修改按钮
        button_html = '<a class="icon fa fa-edit" style="color: green" href="/admin/interface/moduleinfo/%s/update/">修改</a>' % obj.id
        return format_html(button_html)

    update_button.short_description = '<span style="color: green">修改</span>'
    update_button.allow_tags = True

    def delete_button(self, obj):
        # 删除按钮
        button_html = '<a class="icon fa fa-times" style="color: blue" href="/admin/interface/moduleinfo/%s/delete/">删除</a>' % obj.id
        return format_html(button_html)

    delete_button.short_description = '<span style="color: blue">删除</span>'
    delete_button.allow_tags = True

    form_layout = (
        Main(
            Fieldset('模块信息部分',
                     'module_group', 'module_name', 'module_describe'),
        ),
        # Side(
        #     Fieldset('时间部分',
        #              'create_time', 'update_time'),
        # )
    )
    # 详情页面字段分区,请注意不是fieldsets

    list_display = [
        'id',
        'module_group',
        'module_name',
        'module_describe',
        'create_time',
        'update_time',
        'update_button',
        'delete_button',
    ]

    ordering = ("id",)
    search_fields = ("module_name",)
    list_filter = ["create_time"]
    list_display_links = ('id', 'module_group', 'module_name')
    show_detail_fields = ['module_name']
    list_editable = ['module_name']
    raw_id_fields = ('module_group',)
    list_per_page = 10

    batch_fields = (
        'module_name',
        'module_describe'
    )
    # 可批量修改的字段
    actions = [CopyAction, BatchChangeAction]
Exemplo n.º 7
0
class BannerAdmin(object):
    list_display = ('show_img', 'show_title_cn', 'show_title_en', 'show_order')
    form_layout = (Main(Fieldset('图片与顺序', 'img', 'order'),
                        Fieldset('中文题目', 'title_cn', 'subtitle_cn'),
                        Fieldset('英文题目', 'title_en', 'subtitle_en')))
Exemplo n.º 8
0
class UserSetting(object):
    # fieldsets=()
    form_layout = (
        Fieldset('用户信息',
                'avatar',
                'role',
                'username',
                'user_name',
                'mobile',
                'email',
                'gender',
                'comment',
            ),
        Fieldset('用户状态',
                'status',
                'is_staff',
                'is_active',
            ),
        Fieldset('用户权限',
                'groups',
                'user_permissions'
            ),
        Fieldset('用户密码',
                'password',
        ),
        Fieldset(None,
                 )
    )
    # fieldsets = (
    #     ('用户信息', {
    #         'fields': (
    #             'avatar',
    #             'role',
    #             'username',
    #             'user_name',
    #             'mobile',
    #             'email',
    #             'gender',
    #             'comment',
    #         )
    #     }),
    #     ('用户状态', {
    #         'fields': (
    #             'status',
    #             'is_staff',
    #             'is_active',
    #
    #         )
    #     }),
    #     ('用户权限', {
    #         'fields': (
    #             'groups',
    #             'user_permissions'
    #         )
    #     }),
    #     ('用户密码', {
    #         'fields': (
    #             'password',
    #         )
    #     }),
    # )
    list_display = ('id','username','user_name', 'role','gender','unit_name','dept_name','mobile','email', 'status', 'create_time')
    list_filter = ('is_staff', 'gender', 'is_active', 'groups')
    search_fields = ('username','user_name','unit_name', 'dept_name', 'mobile')
    ordering = ('role',)
Exemplo n.º 9
0
class t_stocking_reject_fba_Admin(object):
    search_box_flag = True
    importfile_plugin = True
    fba_tree_menu_flag = True
    hide_page_action = True

    def show_ProductImage(self, obj):
        from Project.settings import BmpUrl
        # 获取图片的url
        picture_url = obj.ProductImage  # 获取图片的url
        sku = obj.ProductSKU  # 获取商品SKU
        if not picture_url:
            picture_url = BmpUrl + sku + '.jpg'

        rt = """<img src="%s"  width="120" height="120"  title="%s" onerror="this.title=''" />  """ % (
            picture_url, picture_url)
        return mark_safe(rt)

    show_ProductImage.short_description = mark_safe(
        '<p align="center" style="width:100px;color:#428bca;">商品图片</p>')

    list_display = ('PurchaseOrderNum', 'RejectNumber', 'RejectDate',
                    'RejectMan', 'ProductSKU', 'ProductName',
                    'show_ProductImage', 'RejectNum', 'RejectStatus',
                    'Remarks')

    fields = ('ProductSKU', 'RejectNum', 'RejectStatus', 'Remarks',
              'PurchaseOrderNum')
    list_editable = (
        'RejectNum',
        'Remarks',
    )
    form_layout = (Fieldset(u'请认真填写备货需求',
                            Row(
                                'ProductSKU',
                                'RejectNum',
                                'RejectStatus',
                            ),
                            Row(
                                'PurchaseOrderNum',
                                '',
                                '',
                            ),
                            Row(
                                'Remarks',
                                '',
                                '',
                            ),
                            css_class='unsort '), )

    actions = ['summitReject', 'not_demand']

    def summitReject(self, request, objs):
        try:
            for obj in objs:
                obj.Status = 'rejecting'
                obj.SummbitRejectMan = request.user.first_name
                obj.SummbitRejectDate = ddtime.now()
                obj.save()
        except Exception, ex:
            messages.info(self.request, "保存报错:%s" % (str(ex)))
Exemplo n.º 10
0
class ChargingPileAdmin(object):
    """
    充电桩管理
    """
    list_display = ['name', 'pile_sn', 'pile_type', 'station', 'pile_mode', 'business_mode',
                    'get_work_status']
    list_display_links = ('name',)
    search_fields = ['pile_sn', 'name', 'pile_type', 'station']
    exclude = ["qrcode", 'group']
    list_filter = ['pile_type', 'station', 'pile_mode', 'business_mode']
    readonly_fields = ['user']

    model_icon = 'fa fa-sitemap'
    show_all_rel_details = False
    # list_editable = ['pile_type', 'pile_sn']
    refresh_times = [3, 5]  # 计时刷新
    save_as = True
    style_fields = {
        "low_restrict": "radio-inline", "low_offset": "radio-inline",
        "subscribe_status": "radio-inline",
        "occupy_status": "radio-inline",
        'sub_status': "radio-inline",
        'charg_mode': "radio-inline",
    }

    form_layout = (
        Main(
            TabHolder(
                Tab(
                    '基础信息设置',
                    Fieldset(
                        '基础信息',
                        Row('name', 'pile_type'),
                        Row('pile_sn', 'power'),
                        Row('station', 'pile_mode'),
                        Row('business_mode', 'fireware'),
                        Row('symbol_4g', 'symbol_eth'),
                        'charg_mode',
                        'sub_time',
                        Row('is_subsidy', 'faults'),
                    ),
                    Inline(ChargingGun),
                    css_id="base_info",
                ),
                Tab(
                    '其他设置',
                    Fieldset(
                        "预约及占位设置",
                        'charg_policy',
                        Row('subscribe_status', AppendedText('subscribe_fee', '元')),
                        Row('occupy_status', AppendedText('occupy_fee', '元')),
                    ),
                    Fieldset(
                        "小电流设置参数",
                        Row('low_restrict', AppendedText('low_cur_value', '毫安')),
                        Row('low_offset', AppendedText('low_offset_value', '元')),
                    ),
                    Fieldset(
                        "单枪参数",
                        Row(AppendedText('gun_max_voltage', '伏'), AppendedText('gun_min_voltage', '伏')),
                        Row(AppendedText('gun_max_current', '安'), AppendedText('gun_min_current', '安')),
                    ),
                    css_id="other_set",
                ),
            ),
        ),
        Side(
            Fieldset("其他信息", 'sub_status',  'user', 'max_gun', 'restart_nums'),
        )
    )

    inlines = [ChargingGunInline]

    def queryset(self):
        queryset = super(ChargingPileAdmin, self).queryset()
        if self.request.user.station:
            return queryset.filter(station=self.request.user.station)
        elif self.request.user.seller:
            return queryset.filter(station__seller=self.request.user.seller)
        else:
            return queryset

    def formfield_for_dbfield(self, db_field,  **kwargs):
        if db_field.name == 'station':
            if not self.request.user.is_superuser:
                kwargs['queryset'] = Station.objects.filter(seller=self.request.user.seller)
        return super(ChargingPileAdmin, self).formfield_for_dbfield(db_field,  **kwargs)

    def save_models(self):
        obj = self.new_obj
        request = self.request
        obj.user = request.user
        obj.group = request.user.groups.first()

        super(ChargingPileAdmin, self).save_models()

    def save_related(self):
        obj = self.new_obj
        super(ChargingPileAdmin, self).save_related()
        for inst in obj.charginggun_set.all():
            self.save_image(inst)

    def save_image(self, instance):
        upload_path = instance.qrcode.field.upload_to
        dirs = os.path.join(settings.MEDIA_ROOT, upload_path)
        if not os.path.exists(dirs):
            os.makedirs(dirs)

        domain_url = settings.ROOT_URL if settings.ROOT_URL else "http://" + self.request.get_host()
        # domain_url = "http://" + self.request.get_host()
        path = reverse('order-prepay', kwargs={'pile_sn': instance.charg_pile.pile_sn, "gun_num": instance.gun_num})
        qrcode_content = '{0}{1}'.format(domain_url, path)
        image = create_qrcode(qrcode_content)
        image_url = '{0}_{1}.png'.format(instance.charg_pile.pile_sn, instance.gun_num)
        image.save(os.path.join(dirs, image_url), quality=100)
        instance.qrcode = '{0}{1}'.format(upload_path, image_url)
        instance.save()

    def station_choices(self, field, request, params, model, model_admin, field_path):
        if self.request.user.station:
            stations = Station.objects.filter(id=self.request.user.station.id).values("id", "name")
        elif self.request.user.seller:
            stations = Station.objects.filter(seller_id=self.request.user.seller.id).values("id", "name")
        else:
            return field.get_choices(include_blank=False)

        return list(((station.get('id'), station.get('name')) for station in stations))
Exemplo n.º 11
0
class ChargingGunAdmin(object):
    list_display = ['charg_pile', 'charging_pile_sn', 'gun_num', 'work_status', 'charg_status', 'cc_status', 'cp_status', 'gun_temp_status', 'elec_lock_status', 'relay_status',]
    search_fields = ['gun_num', 'charg_pile__pile_sn']
    list_display_links = ['gun_num', 'charg_pile']
    list_filter = ['charg_pile', 'work_status']
    model_icon = 'fa fa-sitemap'
    show_all_rel_details = False
    # save_as = True
    # save_on_top = True

    form_layout = (
        Fieldset(
            '枪口信息',
            Row('gun_num', 'charg_pile'),
            Row('gun_type', 'nationalstandard'),
            Row(
                AppendedText('voltage_upper_limits', 'V'),
                AppendedText('voltage_lower_limits', 'V'),
            ),
            Row(
                AppendedText('current', 'A'),
                AppendedText('power', 'KW'),
            ),
            Row('work_status', 'charg_status'),
            Row('cc_status', 'cp_status'),
            Row('gun_temp_status', 'elec_lock_status'),
            Row('relay_status', 'fuse_status'),
            Row('gun_temp', 'cab_temp'),
        ),
        Fieldset(
            '其他信息',
            Row('subscribe_min', "qrcode"),

        ),
        Fieldset(
            '最近订单',
            Row('out_trade_no', 'order_time', ),
        ),
    )

    def queryset(self):
        queryset = super(ChargingGunAdmin, self).queryset()
        if self.request.user.station:
            return queryset.filter(charg_pile__station=self.request.user.station)
        elif self.request.user.seller:
            return queryset.filter(charg_pile__station__seller=self.request.user.seller)
        else:
            return queryset

    def formfield_for_dbfield(self, db_field,  **kwargs):
        if db_field.name == 'charg_pile':
            if self.request.user.is_superuser:
                pass
            elif self.request.user.station:
                kwargs['queryset'] = ChargingPile.objects.filter(station=self.request.user.station)
            elif self.request.user.seller:
                kwargs['queryset'] = ChargingPile.objects.filter(station__seller=self.request.user.seller)

        return super(ChargingGunAdmin, self).formfield_for_dbfield(db_field,  **kwargs)

    def save_models(self):
        obj = self.new_obj
        request = self.request

        upload_path = obj.qrcode.field.upload_to
        dirs = os.path.join(settings.MEDIA_ROOT, upload_path)

        if not os.path.exists(dirs):
            os.makedirs(dirs)

        domain_url = settings.ROOT_URL if settings.ROOT_URL else "http://" + request.get_host()
        # domain_url ="http://" + request.get_host()
        path = reverse('order-prepay', kwargs={'pile_sn': obj.charg_pile.pile_sn, "gun_num": obj.gun_num})
        qrcode_content = '{0}{1}'.format(domain_url, path)
        image = create_qrcode(qrcode_content)
        image_url = '{0}_{1}.png'.format(obj.charg_pile.pile_sn, obj.gun_num)
        image.save(os.path.join(dirs, image_url), quality=100)
        obj.qrcode = '{0}{1}'.format(upload_path, image_url)
        return super(ChargingGunAdmin, self).save_models()

    def charg_pile_choices(self, field, request, params, model, model_admin, field_path):
        if self.request.user.station:
            piles = ChargingPile.objects.filter(station_id=self.request.user.station.id).values("id", "name")
        elif self.request.user.seller:
            piles = ChargingPile.objects.filter(station__seller_id=self.request.user.seller.id).values("id", "name")
        else:
            return field.get_choices(include_blank=False)
        return list(((pile.get('id'), pile.get('name')) for pile in piles))
Exemplo n.º 12
0
class StationAdmin(object):
    list_display = ['id', 'name', 'seller', 'province_city_district', 'address',  'telephone',  'station_status', 'station_type']
    list_display_links = ('name',)
    search_fields = ['name',  'address', 'seller.name', 'telephone', 'telephone1']
    list_filter = ['seller', 'dicount']
    model_icon = 'fa fa-sitemap'
    relfield_style = 'fk_ajax'
    inlines = [StationImageInline]

    form_layout = (
        Main(
            Fieldset(
                '基本信息',
                Row('name', 'seller'),
                Row('province', 'city'),
                Row('district', 'address'),
                Row('equip_owner_id', 'station_status'),
                Row('station_type', 'construction'),
                Row('telephone', 'telephone1'),
                Row('is_show', None),
            ),
            Fieldset(
                '费用收取设置',
                Row(
                    AppendedText('low_restrict_val', '毫安'),
                    AppendedText('low_fee', '元')
                ),
                Row(
                    AppendedText('service_ratio', '%'),
                    AppendedText('rebate_ratio', '%')
                ),
            ),
            Fieldset(
                '离线情况设置',
                Row(
                    AppendedText('offline_sub_fee', '元'),
                    AppendedText('offline_occupy_fee', '元'),
                ),
                Row(
                    AppendedText('offline_low_fee', '元'),
                    'offline_low_restrict',
                )
            ),
        ),
        Side(
            Fieldset(
                '优惠方案',
                'dicount',
                'is_reduction',
                AppendedText('purchase_amount', '元'),
                AppendedText('reduction', '元')
            ),
            Fieldset(
                '地理信息',
                'latitude', 'longitude', 'altitude',
            ),
        ),

    )

    def get_media(self):
        media = super(StationAdmin, self).get_media()
        path = self.request.get_full_path()
        if "add" in path or 'update' in path:
            media.add_js([self.static('stationmanager/js/xadmin.areacode.js')])
        return media

    def queryset(self):
        queryset = super(StationAdmin, self).queryset()
        if self.request.user.station:
            return queryset.filter(id=self.request.user.station.id)
        elif self.request.user.seller:
            return queryset.filter(seller=self.request.user.seller)
        else:
            return queryset

    def seller_choices(self, field, request, params, model, model_admin, field_path):
        if self.request.user.station:
            seller_lst = Seller.objects.filter(id=self.request.user.station.seller.id).values("id", "name")
        elif self.request.user.seller:
            seller_lst = Seller.objects.filter(id=self.request.user.seller.id).values("id", "name")
        else:
            return field.get_choices(include_blank=False)

        return list(((seller.get('id'), seller.get('name')) for seller in seller_lst))

    def formfield_for_dbfield(self, db_field,  **kwargs):
        # print(self.new_obj)
        if db_field.name == 'seller':
            if not self.request.user.is_superuser:
                kwargs['queryset'] = Seller.objects.filter(id=self.request.user.seller.id)

        if db_field.name == 'province':
            kwargs['queryset'] = AreaCode.objects.extra(where=['length(code)=2'])

        if db_field.name == 'city':
            kwargs['queryset'] = AreaCode.objects.extra(where=['length(code)=4'])

        if db_field.name == 'district':
            kwargs['queryset'] = AreaCode.objects.extra(where=['length(code)=6'])

        # if db_field.name == 'fee_scale':
        #     kwargs['queryset'] = AreaCode.objects.extra(where=['length(code)=6'])

        return super(StationAdmin, self).formfield_for_dbfield(db_field,  **kwargs)
Exemplo n.º 13
0
from django.utils.translation import ugettext as _
from xadmin.layout import Fieldset, Main, Side, Row

BasicLayout = \
    (
        Main(
            Fieldset(_('个人信息'),
                     'fam_number',
                     'fam_name',
                     'fam_gender',
                     'fam_id_number',
                     'fam_loc',
                     'fam_class',
                     ),
            Fieldset(_('学历和专业'),
                     'fam_deg',
                     'fam_major',
                     ),
            Fieldset(_('工作信息'),
                     'fam_company',
                     'fam_duty',
                     'fam_status',
                     'fam_origin',
                     ),
            Fieldset(_('联系方式'),
                     'fam_cellphone',
                     'fam_wechat',
                     'fam_qq',
                     ),
            Fieldset(_('报名信息'),
                     'fam_signup_date',
Exemplo n.º 14
0
class ShopInfoAdmin(object):
    list_display = [
        'shop_id', 'name', 'centre', 'company', 'platform', 'create_time',
        'creator'
    ]
    list_filter = ['name']
    search_fields = ['name']
    form_layout = [
        Fieldset('必填信息', 'name', 'shop_id', 'centre', 'platform',
                 'order_status'),
        Fieldset(None, 'creator', 'is_delete', **{"style": "display:None"}),
    ]
    actions = []
    import_data = True

    def post(self, request, *args, **kwargs):

        file = request.FILES.get('file', None)
        if file:
            result = self.handle_upload_file(file)
            if isinstance(result, int):
                self.message_user('导入成功数据%s条' % result['successful'],
                                  'success')
                if result['false'] > 0:
                    self.message_user(
                        '导入失败数据%s条,主要的错误是%s' %
                        (result['false'], result['error']), 'warning')
                if result['repeated'] > 0:
                    self.message_user('包含更新重复数据%s条' % result['repeated'],
                                      'error')
            else:
                self.message_user('结果提示:%s' % result)
        return super(ShopInfoAdmin, self).post(request, *args, **kwargs)

    def handle_upload_file(self, _file):
        INIT_FIELDS_DIC = {'店铺ID': 'shop_id', '店铺名称': 'name', '部门': 'centre'}
        ALLOWED_EXTENSIONS = ['xls', 'xlsx']
        report_dic = {
            "successful": 0,
            "discard": 0,
            "false": 0,
            "repeated": 0,
            "error": []
        }

        if '.' in _file.name and _file.name.rsplit(
                '.')[-1] in ALLOWED_EXTENSIONS:
            with pd.ExcelFile(_file) as xls:
                df = pd.read_excel(xls,
                                   sheet_name=0,
                                   converters={u'店铺ID': str})
                FILTER_FIELDS = ['店铺ID', '店铺名称', '部门']

                try:
                    df = df[FILTER_FIELDS]
                except Exception as e:
                    report_dic["error"].append(e)
                    return report_dic

                # 获取表头,对表头进行转换成数据库字段名
                columns_key = df.columns.values.tolist()
                for i in range(len(columns_key)):
                    columns_key[i] = columns_key[i].replace(' ', '').replace(
                        '=', '')

                for i in range(len(columns_key)):
                    if INIT_FIELDS_DIC.get(columns_key[i], None) is not None:
                        columns_key[i] = INIT_FIELDS_DIC.get(columns_key[i])

                # 验证一下必要的核心字段是否存在
                _ret_verify_field = ShopInfo.verify_mandatory(columns_key)
                if _ret_verify_field is not None:
                    return _ret_verify_field

                # 更改一下DataFrame的表名称
                columns_key_ori = df.columns.values.tolist()
                ret_columns_key = dict(zip(columns_key_ori, columns_key))
                df.rename(columns=ret_columns_key, inplace=True)

                # 获取导入表格的字典,每一行一个字典。这个字典最后显示是个list
                _ret_list = df.to_dict(orient='records')
                intermediate_report_dic = self.save_resources(_ret_list)
                for k, v in intermediate_report_dic.items():
                    if k == "error":
                        if intermediate_report_dic["error"]:
                            report_dic[k].append(v)
                    else:
                        report_dic[k] += v
                return report_dic

        # 以下是csv处理逻辑,和上面的处理逻辑基本一致。
        elif '.' in _file.name and _file.name.rsplit('.')[-1] == 'csv':
            df = pd.read_csv(_file, encoding="GBK", chunksize=300)

            for piece in df:
                # 获取表头
                columns_key = piece.columns.values.tolist()
                # 剔除表头中特殊字符等于号和空格
                for i in range(len(columns_key)):
                    columns_key[i] = columns_key[i].replace(' ', '').replace(
                        '=', '')
                # 循环处理对应的预先设置,转换成数据库字段名称
                for i in range(len(columns_key)):
                    if INIT_FIELDS_DIC.get(columns_key[i], None) is not None:
                        columns_key[i] = INIT_FIELDS_DIC.get(columns_key[i])
                # 直接调用验证函数进行验证
                _ret_verify_field = ShopInfo.verify_mandatory(columns_key)
                if _ret_verify_field is not None:
                    return _ret_verify_field
                # 验证通过进行重新处理。
                columns_key_ori = piece.columns.values.tolist()
                ret_columns_key = dict(zip(columns_key_ori, columns_key))
                piece.rename(columns=ret_columns_key, inplace=True)
                _ret_list = piece.to_dict(orient='records')
                intermediate_report_dic = self.save_resources(_ret_list)
                for k, v in intermediate_report_dic.items():
                    if k == "error":
                        if intermediate_report_dic["error"]:
                            report_dic[k].append(v)
                    else:
                        report_dic[k] += v
            return report_dic

        else:
            return "只支持excel和csv文件格式!"

    def save_resources(self, resource):
        # 设置初始报告
        report_dic = {
            "successful": 0,
            "discard": 0,
            "false": 0,
            "repeated": 0,
            "error": []
        }

        # 开始导入数据
        for row in resource:
            # 判断表格尾部
            order = ShopInfo()  # 创建表格每一行为一个对象
            for k, v in row.items():
                if re.match(r'^=', str(v)):
                    row[k] = v.replace('=', '').replace('"',
                                                        '').replace(' ', '')

            shop_nanme = str(row["name"])
            _q_shop = ShopInfo.objects.filter(name=shop_nanme)
            if _q_shop.exists():
                report_dic["false"] += 1
                report_dic["error"].append('%s店铺已经存在' % shop_nanme)
                continue

            centre = str(row["centre"])
            _q_centre = CentreInfo.objects.filter(name=centre)
            if _q_centre.exists():
                order.centre = _q_centre[0]
            else:
                report_dic["false"] += 1
                report_dic["error"].append('%s不存在此中心' % centre)
                continue

            order.shop_id = row['shop_id']
            order.name = row['name']
            try:
                order.creator = self.request.user.username
                order.save()
                report_dic["successful"] += 1
            # 保存出错,直接错误条数计数加一。
            except Exception as e:
                report_dic["error"].append(e)
                report_dic["false"] += 1
        return report_dic

    def save_models(self):
        obj = self.new_obj
        request = self.request
        obj.creator = request.user.username
        obj.save()
        super(ShopInfoAdmin, self).save_models()
Exemplo n.º 15
0
class InterfaceInfoAdmin(object):
    model = InterfaceInfo
    extra = 1
    # 提供1个足够的选项行,也可以提供N个
    style = "accordion"

    # 折叠

    def update_button(self, obj):
        # 修改按钮
        button_html = '<a class="icon fa fa-edit" style="color: green" href="/admin/interface/interfaceinfo/%s/update/">修改</a>' % obj.id
        return format_html(button_html)

    update_button.short_description = '<span style="color: green">修改</span>'
    update_button.allow_tags = True

    def delete_button(self, obj):
        # 删除按钮
        button_html = '<a class="icon fa fa-times" style="color: blue" href="/admin/interface/interfaceinfo/%s/delete/">删除</a>' % obj.id
        return format_html(button_html)

    delete_button.short_description = '<span style="color: blue">删除</span>'
    delete_button.allow_tags = True

    form_layout = (
        Main(
            Fieldset('用例信息部分',
                     'case_group', 'case_name'),
            Fieldset('接口信息部分',
                     'interface_url', 'request_mode',
                     'request_parameter', 'request_head', 'body_type',
                     'request_body', 'expected_result', 'response_assert',
                     'wait_time'),
            Fieldset('正则表达式提取器',
                     'regular_expression', 'regular_variable', 'regular_template'),
        ),
        Side(
            # Fieldset('响应信息部分',
            #          'response_code', 'actual_result', 'pass_status'),
            # Fieldset('时间部分',
            #          'create_time', 'update_time'),
        )
    )
    # 详情页面字段分区,请注意不是fieldsets

    list_display = [
        'id',
        'case_group',
        'case_name',
        'interface_url',
        'request_mode',
        'request_parameter',
        'request_head',
        'body_type',
        'request_body',
        'expected_result',
        'response_assert',
        'wait_time',
        'regular_expression',
        'regular_variable',
        'regular_template',
        'response_code',
        'actual_result',
        'pass_status',
        'create_time',
        'update_time',
        'update_button',
        'delete_button',
    ]

    ordering = ("id",)
    search_fields = ("case_name",)
    list_filter = ["pass_status", "create_time"]
    list_display_links = ('id', 'case_group', 'case_name')
    show_detail_fields = ['case_name']
    list_editable = ['case_name']
    readonly_fields = ['response_code', 'actual_result', 'pass_status']
    raw_id_fields = ('case_group',)
    list_per_page = 10

    batch_fields = (
        'case_name',
        'interface_url',
        'request_mode',
        'request_parameter',
        'request_head',
        'body_type',
        'request_body',
        'expected_result',
        'response_assert',
        'wait_time',
        'regular_expression',
        'regular_variable',
        'regular_template',
    )
    # 可批量修改的字段
    actions = [CopyAction, BatchChangeAction]
Exemplo n.º 16
0
 def get_form_layout(self):
     if self.org_obj:
         self.form_layout = (Main(
             Fieldset(
                 _('基本信息'),
                 'company_name',
                 'company_type',
                 'url',
                 'legal_man',
                 'issue_date',
                 'registration_authority',
             ),
             Fieldset(
                 _('联系人物'),
                 'link_man',
                 'sex',
                 'job',
                 'is_boss',
                 'isboss_mobile',
             ),
             Fieldset(_('联系方式'), 'tel_phone', 'mobile_phone',
                      'mobile_phone_address', 'mobile_carrieroperator',
                      'zip_code'),
             Fieldset(
                 _('主要经营'),
                 'scope_business',
                 'business_position',
                 'produce_address',
             ),
             Fieldset(
                 _('地址详情'),
                 'province',
                 'prefecture_level_city',
                 'county_district',
                 'address',
             ),
             Fieldset(
                 _('注册日期'),
                 'register_year',
                 'register_month',
                 'register_date',
             ),
             Fieldset(
                 _('财务信息'),
                 'finance_principal',
                 'finance_principal_mobile',
             ),
             Fieldset(
                 _('渠道信息'),
                 'channel',
             ),
             Fieldset(
                 _('意向信息'),
                 'seo_status',
                 'aike_status',
             ),
             Fieldset(
                 _('时间信息'),
                 'create_date',
                 'update_date',
             ),
         ), Side())
     return super(SEOCustomerAdmin, self).get_form_layout()
Exemplo n.º 17
0
class PerformanceInfoAdmin(object):

    def update_button(self, obj):
        # 修改按钮
        button_html = '<a class="icon fa fa-edit" style="color: green" href="/admin/interface/performanceinfo/%s/update/">修改</a>' % obj.id
        return format_html(button_html)

    update_button.short_description = '<span style="color: green">修改</span>'
    update_button.allow_tags = True

    def delete_button(self, obj):
        # 删除按钮
        button_html = '<a class="icon fa fa-times" style="color: blue" href="/admin/interface/performanceinfo/%s/delete/">删除</a>' % obj.id
        return format_html(button_html)

    delete_button.short_description = '<span style="color: blue">删除</span>'
    delete_button.allow_tags = True

    def download_button(self, obj):
        # 下载按钮
        button_html = '<a class="icon fa fa-download" style="color: orange" href="/media/%s">下载</a>' % obj.jmeter_script
        return format_html(button_html)

    download_button.short_description = '<span style="color: orange">下载</span>'
    download_button.allow_tags = True

    form_layout = (
        Main(
            Fieldset('压测信息部分',
                     'script_introduce', 'jmeter_script',
                     'sample_number', 'duration'),
        ),
        # Side(
        #     Fieldset('时间部分',
        #              'create_time', 'update_time'),
        # )
    )

    list_display = [
        'id',
        'script_introduce',
        'jmeter_script',
        'sample_number',
        'duration',
        'run_sum',
        'create_time',
        'update_time',
        'download_button',
        'update_button',
        'delete_button',
    ]
    ordering = ("id",)
    search_fields = ("script_introduce",)
    list_filter = ["script_introduce", "create_time"]
    show_detail_fields = ['script_introduce']
    list_display_links = ('id', 'script_introduce')
    list_editable = ['script_introduce']
    list_per_page = 10

    batch_fields = (
        'script_introduce',
        'sample_number',
        'duration',
    )
    # 可批量修改的字段
    actions = [CopyAction, BatchChangeAction]
class t_product_questions_outAdmin(object):
    search_box_flag = True    
    def show_AttachmentUrls(self,obj) :
        attachmentUrl1="";
        attachmentUrl2="";
        attachmentUrl3="";
        attachmentUrl4="";
        attachmentUrl5="";
        attachmentUrl6="";
        rt=''
        if obj.AttachmentUrl1 is not None and str(obj.AttachmentUrl1).strip() !='' :
            attachmentUrl1 =  u'%s%s.%s/%s/%s/%s'%(PREFIX,BUCKETNAME_TORT,ENDPOINT_OUT,'questions',obj.id,str(obj.AttachmentUrl1))
            rt="%s附件一:<a href=%s>%s</a>;<br>"%(rt,attachmentUrl1,attachmentUrl1)
        if obj.AttachmentUrl2 is not None and str(obj.AttachmentUrl2).strip() !='' :
            attachmentUrl2 =  u'%s%s.%s/%s/%s/%s'%(PREFIX,BUCKETNAME_TORT,ENDPOINT_OUT,'questions',obj.id,str(obj.AttachmentUrl2))
            rt="%s附件二:<a href=%s>%s</a>;<br>"%(rt,attachmentUrl2,attachmentUrl2)
        if obj.AttachmentUrl3 is not None and str(obj.AttachmentUrl3).strip() !='' :
            attachmentUrl3 =  u'%s%s.%s/%s/%s/%s'%(PREFIX,BUCKETNAME_TORT,ENDPOINT_OUT,'questions',obj.id,str(obj.AttachmentUrl3))
            rt="%s附件三:<a href=%s>%s</a>;<br>"%(rt,attachmentUrl3,attachmentUrl3)
        if obj.AttachmentUrl4 is not None and str(obj.AttachmentUrl4).strip() !='' :
            attachmentUrl4 =  u'%s%s.%s/%s/%s/%s'%(PREFIX,BUCKETNAME_TORT,ENDPOINT_OUT,'questions',obj.id,str(obj.AttachmentUrl4))
            rt="%s附件四:<a href=%s>%s</a>;<br>"%(rt,attachmentUrl4,attachmentUrl4)
        if obj.AttachmentUrl5 is not None and str(obj.AttachmentUrl5).strip() !='' :
            attachmentUrl5 =  u'%s%s.%s/%s/%s/%s'%(PREFIX,BUCKETNAME_TORT,ENDPOINT_OUT,'questions',obj.id,str(obj.AttachmentUrl5))
            rt="%s附件五:<a href=%s>%s</a>;<br>"%(rt,attachmentUrl5,attachmentUrl5)
        if obj.AttachmentUrl6 is not None and str(obj.AttachmentUrl6).strip() !='' :
            attachmentUrl6 =  u'%s%s.%s/%s/%s/%s'%(PREFIX,BUCKETNAME_TORT,ENDPOINT_OUT,'questions',obj.id,str(obj.AttachmentUrl6))
            rt="%s附件六:<a href=%s>%s</a>;"%(rt,attachmentUrl6,attachmentUrl6)

        #rt =  "附件一:<a href=%s>%s</a>;<br>附件二:<a href=%s>%s</a><br>附件三:<a href=%s>%s</a><br>附件四:<a href=%s>%s</a><br>附件五:<a href=%s>%s</a><br>附件六:<a href=%s>%s</a>;"%(attachmentUrl1,attachmentUrl1,attachmentUrl2,attachmentUrl2,attachmentUrl3,attachmentUrl3,attachmentUrl4,attachmentUrl4,attachmentUrl5,attachmentUrl5,attachmentUrl6,attachmentUrl6)
        return mark_safe(rt)
    show_AttachmentUrls.short_description = u'附件'
    
    
    list_display=('id','PTitle','Type','Priority','LevelNumber','SubmitDay','Status','StaffIDSubmit','StaffIDCheck','StaffIDHandle','Remark','StaffID','Description','show_AttachmentUrls','UpdateTime',)
    list_display_links=('id',)
    search_fields=('id','Type','PTitle','Priority','LevelNumber','Status','StaffIDSubmit','StaffIDHandle','StaffID','Description','StaffIDCheck',)
    list_filter = ('PTitle','Type','Priority','LevelNumber','SubmitDay','ExpectedDay','Status','StaffIDSubmit','StaffIDHandle','StaffID','Description','UpdateTime','StaffIDCheck','ExecutedDay')
    readonly_fields = ('id','UpdateTime',)
    list_editable = ('PTitle','Type','Priority','LevelNumber','SubmitDay','ExpectedDay','Status','StaffIDSubmit','StaffIDHandle','Remark','StaffID','Description','StaffIDCheck','ExecutedDay',)

    form_layout = (
        Fieldset(u'基本信息',
                       Row('id','StaffID',),
                       Row('PTitle','Type','Status',),
                       Row('Priority','SubmitDay','ExpectedDay',),
                       Row('StaffIDSubmit','StaffIDCheck'),
                       Row('StaffIDHandle','ExecutedDay',),
                       css_class = 'unsort '
                ),
        Fieldset(u'问题描述',
                       Row( 'AttachmentUrl1','AttachmentUrl2'),
                       Row( 'AttachmentUrl3','AttachmentUrl4'),
                       Row( 'AttachmentUrl5','AttachmentUrl6'),
                       Row( 'Description',),
                       css_class = 'unsort  '
                ),
        Fieldset(u'更新时间',
                       Row('UpdateTime',),
                       css_class = 'unsort '
                )
                  )
    
    def get_list_queryset(self):
        request = self.request
        qs = super(t_product_questions_Adimin, self).get_list_queryset()
        return qs.exclude(Status="已完成")

        logger = logging.getLogger('sourceDns.webdns.views')
    #def save_model(self, request, obj, form, change):
    def save_models(self):
        obj = self.new_obj
        request = self.request
        import datetime
        now = datetime.datetime.now()
        
        auth = oss2.Auth(ACCESS_KEY_ID, ACCESS_KEY_SECRET)
        bucket = oss2.Bucket(auth, ENDPOINT,BUCKETNAME_TORT)
        try:

            if obj.AttachmentUrl1 is not None and str(obj.AttachmentUrl1).strip() !='' :
                bucket.put_object(u'%s/%s/%s'%('questions',obj.id,str(obj.AttachmentUrl1)),obj.AttachmentUrl1)

            if obj.AttachmentUrl2 is not None and str(obj.AttachmentUrl2).strip() !='' :
                bucket.put_object(u'%s/%s/%s'%('questions',obj.id,str(obj.AttachmentUrl2)),obj.AttachmentUrl2)

            if obj.AttachmentUrl3 is not None and str(obj.AttachmentUrl3).strip() !='' :
                bucket.put_object(u'%s/%s/%s'%('questions',obj.id,str(obj.AttachmentUrl3)),obj.AttachmentUrl3)

            if obj.AttachmentUrl4 is not None and str(obj.AttachmentUrl4).strip() !='' :
                bucket.put_object(u'%s/%s/%s'%('questions',obj.id,str(obj.AttachmentUrl4)),obj.AttachmentUrl4)

            if obj.AttachmentUrl5 is not None and str(obj.AttachmentUrl5).strip() !='' :
                bucket.put_object(u'%s/%s/%s'%('questions',obj.id,str(obj.AttachmentUrl5)),obj.AttachmentUrl5)

            if obj.AttachmentUrl6 is not None and str(obj.AttachmentUrl6).strip() !='' :
                bucket.put_object(u'%s/%s/%s'%('questions',obj.id,str(obj.AttachmentUrl6)),obj.AttachmentUrl6)
        except:
            pass
         
        obj.StaffID = request.user.username
        obj.save()
        if request.method == 'POST':
            files = request.FILES.getlist('myfiles')
            for f in files :
                path = MEDIA_ROOT + 'questions_pic/' + str(obj.id)
                if not os.path.exists(path):
                    os.mkdir(path)
                destination = open(path + '/' +  f.name,'wb+')
                for chunk in f.chunks():
                  destination.write(chunk)
                destination.close()
        
    def get_list_queryset(self):
        request = self.request
        qs = super(t_product_questions_outAdmin, self).get_list_queryset()
        
        status       = request.GET.get('status','')           #状态
        
        searchList = {  'Status__exact':status, 
                        }
                                
        sl = {}
        for k,v in searchList.items():
            if isinstance(v,list):
                if v:
                    sl[k] = v
            else:
                if v is not None and v.strip() != '':
                    #if k == 'ShopName__exact':
                        #v = 'Wish-' + v.zfill(4)
                        # messages.error(request, v)
                    sl[k] = v
        if sl is not None:
            # messages.error(request, sl)
            try:
                qs = qs.filter(**sl)
            except Exception,ex:
                messages.error(request,u'输入的查询数据有问题!')
                                
        return qs.filter(IT_IN_OUT='OUT')
Exemplo n.º 19
0
class t_progress_tracking_of_product_customization_table_Admin(object):
    search_box_flag = True
    show_prompt_develop = True
    left_flag = True

    list_per_page = 20

    def del_None(self, col):
        return col if col else ''

    def readonly(self, obj):
        return 'readonly' if obj.RateOfProgress == '2' else ''

    def show_Image(self, obj):
        rt = '<img src="{}" width="172" height="172"></img>'.format(
            obj.ImageURL)
        return mark_safe(rt)

    show_Image.short_description = u'图片'

    def show_person_time_info(self, obj):
        rt = u'提交人:%s' % self.del_None(obj.Submiter)
        rt = rt + u' 提交时间:%s' % self.del_None(obj.SubmitTime)
        rt = rt + u'<br>调研员:<input value="%s" style="border:none;background-color:transparent;" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'t_progress_tracking_of_product_customization_table\')" %s title="%s"/><span id="%s"></span>' % \
              (self.del_None(obj.SurveyPerson), obj.id, 'SurveyPerson', self.readonly(obj),self.del_None(obj.SurveyPerson), str(obj.id) + '_SurveyPerson')
        rt = rt + u'</br>调研时间:<input value="%s" style="border:none;background-color:transparent;" type="datetime-local" onchange="to_change_work(\'%s\',\'%s\',this.value,\'t_progress_tracking_of_product_customization_table\')" %s title="%s"/><span id="%s"></span>' % \
             (obj.SurveyTime.strftime('%Y-%m-%dT%H:%M') if obj.SurveyTime else '', obj.id, 'SurveyTime', self.readonly(obj),self.del_None(obj.SurveyTime), str(obj.id) + '_SurveyTime')
        rt = u'%s </br>供应链开发员:<input value="%s" style="border:none;background-color:transparent;" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'t_progress_tracking_of_product_customization_table\')" %s title="%s"/><span id="%s"></span>' % \
             (rt, self.del_None(obj.SupplyChainDeveloper), obj.id, 'SupplyChainDeveloper', self.readonly(obj),self.del_None(obj.SupplyChainDeveloper), str(obj.id) + '_SupplyChainDeveloper')
        rt = u'%s</br>计划完成时间:<input value="%s" style="border:none;background-color:transparent;" type="datetime-local" onchange="to_change_work(\'%s\',\'%s\',this.value,\'t_progress_tracking_of_product_customization_table\')" %s title="%s"/><span id="%s"></span>' % \
             (rt, obj.FinishTime.strftime('%Y-%m-%dT%H:%M') if obj.FinishTime else '',obj.id,'FinishTime', self.readonly(obj),self.del_None(obj.FinishTime),str(obj.id)+'_FinishTime')
        rt = u'%s </br>审核人:<input value="%s" style="border:none;background-color:transparent;" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'t_progress_tracking_of_product_customization_table\')" %s title="%s"/><span id="%s"></span>' % \
             (rt, self.del_None(obj.CheckPerson), obj.id, 'CheckPerson', self.readonly(obj),self.del_None(obj.CheckPerson), str(obj.id) + '_CheckPerson')
        rt = u'%s</br>审核时间:%s' % (
            rt,
            self.del_None(obj.CheckTime),
        )
        rt = rt + u'</br>完成操作人:%s' % self.del_None(obj.DonePerson)
        rt = rt + u' 完成时间:%s' % self.del_None(obj.DoneTime)
        return mark_safe(rt)

    show_person_time_info.short_description = mark_safe(
        u'<p align="center"style="color:#428bca;width:340px;">人员/时间信息</p>')

    def show_product_info(self, obj):
        rt = u'产品名称:<input value="%s" style="border:none;background-color:transparent;" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'t_progress_tracking_of_product_customization_table\')" %s title="%s"/><span id="%s"></span>' % \
             (self.del_None(obj.Name), obj.id, 'Name', self.readonly(obj), self.del_None(obj.Name), str(obj.id) + '_Name')

        skuname = '<span style="color: red;">SKU</span>'
        if obj.SKU and obj.SKU.strip() != 'N/A':
            skuname = 'SKU'

        rt = u'%s </br>%s:<input value="%s" style="border:none;background-color:transparent;" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'t_progress_tracking_of_product_customization_table\')" %s title="%s"/><span id="%s"></span>' % \
             (rt, skuname, self.del_None(obj.SKU), obj.id, 'SKU', self.readonly(obj), self.del_None(obj.SKU),str(obj.id) + '_SKU')
        rt = u'%s </br>关键字:<input value="%s" style="border:none;background-color:transparent;" type="text" onchange="to_change_work(\'%s\',\'%s\',this.value,\'t_progress_tracking_of_product_customization_table\')" %s title="%s"/><span id="%s"></span>' % \
             (rt, self.del_None(obj.KeyWords), obj.id, 'KeyWords', self.readonly(obj), self.del_None(obj.KeyWords), str(obj.id) + '_KeyWords')
        rt = u'%s</br>' % rt

        if obj.RateOfProgress in [
                '0', '1'
        ] and obj.FinishTime and obj.FinishTime.strftime(
                '%Y-%m-%d %H:%M:%S') < datetime.now().strftime(
                    '%Y-%m-%d %H:%M:%S'):
            if obj.RateOfProgress == '0':
                rt = rt + u'<div style="background:red;color:white">已超过计划时间,待审核</div>'
            elif obj.RateOfProgress == '1':
                rt = rt + u'<div style="background:red;color:white">已超过计划时间,待完成</div>'
        elif obj.RateOfProgress == '0' and obj.FinishTime and obj.FinishTime.strftime(
                '%Y-%m-%d %H:%M:%S') >= datetime.now().strftime(
                    '%Y-%m-%d %H:%M:%S'):
            rt = rt + u'<div style="background:#9E3F3F;color:white">待审核</div>'
        elif obj.RateOfProgress == '1':
            rt = rt + u'<div style="background:green;color:white">已审核,生产中</div>'
        elif obj.RateOfProgress == '2':
            rt = rt + u'<div style="background:green;color:white">已完成</div>'
        elif obj.RateOfProgress == '-1':
            rt = rt + u'<div style="background:dimgrey;color:white">被废弃</div>'

        rt = rt + u'<br>反向链接:<a title="%s" href="%s" target="_blank">%s...</a>' % \
             (obj.ReverseLink, obj.ReverseLink, self.del_None(obj.ReverseLink)[:25])
        rt = u'%s</br>1688链接:<a title="%s" href="%s" target="_blank">%s...</a>' % \
             (rt, obj.SupplierLink, obj.SupplierLink, self.del_None(obj.SupplierLink)[:25])
        rt = u'%s</br>附件下载:<a title="%s" href="%s" target="_blank">%s...</a>' % \
             (rt, obj.Enclosure, obj.Enclosure, str(obj.Enclosure)[:25])

        return mark_safe(rt)

    show_product_info.short_description = mark_safe(
        u'<p align="center"style="color:#428bca;width:310px;">产品信息</p>')

    def show_SurveyAnalysis(self, obj):
        rt = u'<textarea style="width:100%%;border:none;background-color:transparent;" rows="6" onchange="to_change_work(\'%s\',\'%s\',this.value,\'t_progress_tracking_of_product_customization_table\')" %s title="%s"> %s </textarea><br><span id="%s"></span>' % \
             (obj.id,'SurveyAnalysis',self.readonly(obj),self.del_None(obj.SurveyAnalysis),self.del_None(obj.SurveyAnalysis),str(obj.id)+'_SurveyAnalysis')
        return mark_safe(rt)

    show_SurveyAnalysis.short_description = mark_safe(
        u'<p align="center"style="color:#428bca;width:225px;">调研分析</p>')

    def show_MakeDemand(self, obj):
        rt = u'<textarea style="width:100%%;border:none;background-color:transparent;" rows="6" onchange="to_change_work(\'%s\',\'%s\',this.value,\'t_progress_tracking_of_product_customization_table\')" %s title="%s"> %s </textarea><br><span id="%s"></span>' % \
             (obj.id,'MakeDemand',self.readonly(obj),self.del_None(obj.MakeDemand),self.del_None(obj.MakeDemand),str(obj.id)+'_MakeDemand')
        return mark_safe(rt)

    show_MakeDemand.short_description = mark_safe(
        u'<p align="center"style="color:#428bca;width:225px;">定做要求</p>')

    def show_DevelopRemark(self, obj):
        rt = u'<textarea style="width:100%%;border:none;background-color:transparent;" rows="6" onchange="to_change_work(\'%s\',\'%s\',this.value,\'t_progress_tracking_of_product_customization_table\')" %s title="%s"> %s </textarea><br><span id="%s"></span>' % \
             (obj.id,'DevelopRemark',self.readonly(obj),self.del_None(obj.DevelopRemark),self.del_None(obj.DevelopRemark),str(obj.id)+'_DevelopRemark')
        return mark_safe(rt)

    show_DevelopRemark.short_description = mark_safe(
        u'<p align="center"style="color:#428bca;width:225px;">开发备注</p>')

    def show_CheckRemark(self, obj):
        rt = u'<textarea style="width:100%%;border:none;background-color:transparent;" rows="6" onchange="to_change_work(\'%s\',\'%s\',this.value,\'t_progress_tracking_of_product_customization_table\')" %s title="%s"> %s </textarea><br><span id="%s"></span>' % \
             (obj.id,'CheckRemark',self.readonly(obj),self.del_None(obj.CheckRemark),self.del_None(obj.CheckRemark),str(obj.id)+'_CheckRemark')
        return mark_safe(rt)

    show_CheckRemark.short_description = mark_safe(
        u'<p align="center"style="color:#428bca;width:225px;">审核意见</p>')

    list_display = (
        'id',
        'show_Image',
        'show_product_info',
        'show_SurveyAnalysis',
        'show_MakeDemand',
        'show_DevelopRemark',
        'show_CheckRemark',
        'show_person_time_info',
    )

    fields = ['MainSKU', 'Enclosure']
    form_layout = (Fieldset(u'检索信息',
                            Row(
                                'MainSKU',
                                'Enclosure',
                            ),
                            css_class='unsort '), )

    actions = ['to_check', 'to_complete', 'to_nullify']

    def to_check(self, request, objs):

        isClothes = request.GET.get('clothes', '0')
        if isClothes == '1':
            messages.warning(request, u'定做服装无须审核....')
            return

        for obj in objs:
            if obj.RateOfProgress == '0' and (obj.CheckPerson
                                              == request.user.first_name
                                              or not obj.CheckPerson):
                obj.RateOfProgress = '1'
                obj.CheckPerson = request.user.first_name
                obj.CheckTime = datetime.now()
                obj.save()

    to_check.short_description = u'审核'

    def to_complete(self, request, objs):
        objs.filter(RateOfProgress='1',
                    SKU__isnull=False).exclude(SKU='').exclude(
                        SKU='N/A').update(RateOfProgress='2',
                                          DonePerson=request.user.first_name,
                                          DoneTime=datetime.now())

    to_complete.short_description = u'完成'

    def to_nullify(self, request, objs):
        isClothes = request.GET.get('clothes', '0')
        if isClothes == '1':
            messages.warning(request, u'定做服装不能废弃....')
            return

        objs.filter(RateOfProgress__in=['0', '1']).update(
            RateOfProgress='-1',
            DonePerson=request.user.first_name,
            DoneTime=datetime.now())

    to_nullify.short_description = u'废弃'

    def save_models(self):
        obj = self.new_obj
        old_obj = None
        if obj is None or obj.id is None or obj.id <= 0:
            pass
        else:
            old_obj = self.model.objects.get(pk=obj.pk)

        try:
            clothes = self.request.GET.get('clothes', '0')
            v_progress = clothes
            if clothes == '1':
                self.request.POST[
                    '_redirect'] = "/Project/admin/skuapp/t_progress_tracking_of_product_customization_table/?clothes=1"

            bemainsku = classsku(connection).get_bemainsku_by_sku(obj.MainSKU)

            enclosure = obj.Enclosure
            if obj.Enclosure:
                filename = '%s/%s/%s' % (
                    self.request.user.username,
                    datetime.now().strftime('%Y%m%d%H%M%S'), obj.Enclosure)
                auth = oss2.Auth(ACCESS_KEY_ID, ACCESS_KEY_SECRET)
                bucket = oss2.Bucket(auth, ENDPOINT, BUCKETNAME_DOWNLOAD)
                presult = bucket.put_object(filename, obj.Enclosure)
                _content = presult.__dict__
                enclosure = PREFIX + BUCKETNAME_DOWNLOAD + '.' + ENDPOINT_OUT + '/' + filename
                if _content['status'] != 200:
                    raise Exception(u'附件上传失败!请稍后重试  code: %s' %
                                    _content['status'])

            image_list = self.request.POST.getlist('product_image', [])
            sku_list = self.request.POST.getlist('sku', [])
            name_list = self.request.POST.getlist('name', [])
            keyword_list = self.request.POST.getlist('keywords', [])
            surveyname_list = self.request.POST.getlist('surveyname', [])
            surveytime_list = self.request.POST.getlist('surveytime', [])
            reverselink_list = self.request.POST.getlist('reverselink', [])
            supplierlink_list = self.request.POST.getlist('supplierlink', [])
            developer_list = self.request.POST.getlist('salerName2', [])
            finishtime_list = self.request.POST.getlist('FinishTime', [])

            insert_into = []
            for i in range(len(sku_list)):
                insert_into.append(
                    self.model(ImageURL=image_list[i],
                               MainSKU=bemainsku,
                               SKU=sku_list[i],
                               Name=name_list[i],
                               KeyWords=keyword_list[i],
                               ReverseLink=reverselink_list[i],
                               SupplierLink=supplierlink_list[i],
                               SurveyPerson=surveyname_list[i],
                               SurveyTime=surveytime_list[i],
                               SupplyChainDeveloper=developer_list[i],
                               FinishTime=finishtime_list[i],
                               SurveyAnalysis='',
                               MakeDemand='',
                               DevelopRemark='',
                               CheckPerson='',
                               CheckTime=None,
                               CheckRemark='',
                               RateOfProgress=v_progress,
                               Enclosure=enclosure,
                               Submiter=self.request.user.first_name,
                               SubmitTime=datetime.now(),
                               FromClothes=clothes))

            self.model.objects.bulk_create(insert_into)

        except Exception, e:
            messages.error(self.request, u'%s:%s' % (Exception, e))
Exemplo n.º 20
0
class PostAdmin(BaseOwnerAdmin):
    form = PostAdminForm
    list_display = [
        'title',
        'category',
        'status_show',
        'pv',
        'uv',
        'owner',
        'created_time',
        'operator']
    # category、status变为可点链接
    # list_display_links = ['category', 'status_show', 'title']
    search_fields = ['title', 'category__name', 'owner__username']
    list_filter = ['owner']
    # 动作按钮在上
    actions_on_top = True
    # 动作按钮在底部
    actions_on_bottom = False
    # 创建时间
    date_hierarchy = 'created_time'
    # 展示可编辑项
    # list_editable = ['title']

    '''
    编辑页面
    '''
    # 增加删除保存键置顶
    # save_on_top = True
    # 要展示的字段
    # fields = (
    #     'title', 'category',
    #     'tag',
    #     'desc',
    #     'status',
    #     'content', 'is_markdown',
    # )
    exclude = (
        'html', 'owner', 'html', 'pv', 'uv',
    )
    form_layout = (
        Fieldset(
            "基础信息",
            'title',
            'desc',
            Row('category', 'tag', 'status'),
            'is_markdown',
            'content',
        ),
    )
    #

    # status不展示
    # exclude = ('status',)
    # fieldsets = (  # 跟fields互斥
    #     ('基础设置', {
    #         'fields': (('category', 'title'),
    #                    'desc',
    #                    'status',  # TODO(Treehl): 后面添加的字段
    #                    'content')
    #     }),
    #     ('高级设置', {
    #         'classes': ('collapse', 'addon'),
    #         'fields': ('tag',),
    #     }),
    # )
    # 水平布局
    # filter_horizontal = ('tag', )
    # 垂直布局
    # filter_vertical = ('tag',)

    def operator(self, obj):
        return format_html(
            '<a href="{}">编辑</a>',
            reverse('cus_admin:blog_post_change', args=(obj.id,))
        )

    operator.short_description = '操作'
Exemplo n.º 21
0
class PresidentAddressAdmin(RichTextAdmin):
    form_layout = (Main(Fieldset('中文致辞', 'address_cn'),
                        Fieldset('英文致辞', 'address_en')), )
Exemplo n.º 22
0
class MicroserviceAdmin(object):
    inlines = [CaseAdmin]

    # 使用内嵌显示

    def case_total(self, obj):
        # 利用外键反向统计用例总数
        button_html = '<span style="color: brown">%s</span>' % obj.microservices.all(
        ).count()
        return format_html(button_html)

    case_total.short_description = '<span style="color: brown">用例总数</span>'
    case_total.allow_tags = True

    def debug_button(self, obj):
        # 调试按钮

        button = '<a class="icon fa fa-bug" style="color: purple" href="debug_microservice/%s">调试</a>' % obj.id
        return mark_safe(button)

    debug_button.short_description = '<span style="color: purple">调试</span>'
    debug_button.allow_tags = True

    def debug_microservice(self):
        # 调试微服务

        logger.info("**********手动调试微服务开始**********\n")

        global pass_status, fail_reason, actual_result_text_re
        variable_result_dict = {}
        # 定义一个变量名与提取的结果字典

        data_object = Microservice.objects.filter(microservice_on_off="开").get(
            id=self).microservices.values_list("id").filter(
                case_on_off="开").order_by("id")
        # 反向查询微服务包含的用例信息
        data_tuple = tuple(data_object)
        # 把QuerySet对象转换成元祖
        data_tuple = tuple(chain.from_iterable(data_tuple))
        # 把多维元祖转换成一维元祖

        for case_i in data_tuple:
            case_object = Case.objects.get(
                id=case_i, case_on_off="开").step_key.values().order_by("id")
            # 反向查询用例包含的步骤信息
            case_name = Case.objects.get(id=case_i).case_name
            logger.info("用例名称为:{}".format(case_name))
            case_list = list(case_object)
            # 把QuerySet对象转换成列表
            for step_i in case_list:
                step_id = step_i["id"]
                step_name = step_i["step_name"]
                request_mode = step_i["request_mode"]
                api = step_i["api"]
                body = step_i["body"]
                headers = step_i["headers"]
                query_string = step_i["query_string"]
                expected_time = step_i["expected_time"]
                expected_code = step_i["expected_code"]
                expected_result = step_i["expected_result"]
                regular = step_i["regular"]

                if variable_result_dict:
                    if api:
                        api = function_dollar(api,
                                              variable_result_dict.items())
                    if body:
                        body = function_dollar(body,
                                               variable_result_dict.items())
                    if headers:
                        headers = function_dollar(headers,
                                                  variable_result_dict.items())
                    if query_string:
                        query_string = function_dollar(
                            query_string, variable_result_dict.items())
                    if expected_result:
                        expected_result = function_dollar(
                            expected_result, variable_result_dict.items())

                if api:
                    api = function_rn(api)
                    api = function_rl(api)
                if body:
                    body = function_rn(body)
                    body = function_rl(body)
                    body = function_mp(body)
                if headers:
                    headers = function_rn(headers)
                    headers = function_rl(headers)
                    headers = function_mp(headers)
                    headers = json.loads(headers)
                if query_string:
                    query_string = function_rn(query_string)
                    query_string = function_rl(query_string)
                    query_string = function_mp(query_string)
                    query_string = json.loads(query_string)

                logger.info("步骤名称为:{}".format(step_name))
                service_domain = Step.objects.get(
                    id=step_id
                ).step_case.case_microservice.microservice_environment.domain_name
                url = service_domain + api
                logger.info("请求地址为:{}".format(url))
                dingtalk_switch = Step.objects.get(
                    id=step_id).step_case.dingtalk_on_off
                logger.info("钉钉开关为:{}".format(dingtalk_switch))

                try:
                    response = requests.request(request_mode,
                                                url,
                                                data=body,
                                                headers=headers,
                                                params=query_string,
                                                timeout=(15, 20))
                    logger.info("HTTP请求成功")
                except Exception as e:
                    logger.error("HTTP请求发生错误:{}".format(e))
                    if dingtalk_switch == "开":
                        alarm_message = http_request_exception_alarm(
                            case_name, step_name, url, request_mode, body,
                            headers, query_string, str(e))
                        send_dingtalk_alarm(alarm_message)
                        logger.info("钉钉报警发送成功")
                    raise e

                try:
                    actual_time = response.elapsed.total_seconds()
                    logger.info("实际的响应时间为:{}".format(actual_time))
                except Exception as e:
                    logger.error("获取实际的响应时间发生错误:{}".format(e))
                    raise e
                try:
                    actual_code = response.status_code
                    logger.info("实际的响应代码为:{}".format(actual_code))
                except Exception as e:
                    logger.error("获取实际的响应代码发生错误:{}".format(e))
                    raise e
                try:
                    actual_result_text = response.text
                    logger.info("实际的响应结果为:{}".format(
                        actual_result_text[0:300]))
                except Exception as e:
                    logger.error("获取实际的响应结果发生错误:{}".format(e))
                    raise e

                if regular:
                    regular = demjson.decode(regular)
                    extract_list = []
                    for i in regular["expression"]:
                        regular_result = re.findall(i, actual_result_text)[0]
                        extract_list.append(regular_result)
                    variable_result_dict_temporary = dict(
                        zip(regular["variable"], extract_list))
                    for key, value in variable_result_dict_temporary.items():
                        variable_result_dict[key] = value

                if variable_result_dict:
                    for key in list(variable_result_dict.keys()):
                        if not variable_result_dict[key]:
                            del variable_result_dict[key]

                expected_result = re.sub("{|}|\'|\"|\\[|\\]| ", "",
                                         expected_result)
                if actual_result_text:
                    actual_result_text_re = re.sub("{|}|\'|\"|\\[|\\]| ", "",
                                                   actual_result_text)
                expected_result_list = re.split(":|,", expected_result)
                actual_result_list_sp = re.split(":|,", actual_result_text_re)

                if expected_code == actual_code:
                    fail_reason = ""
                    if set(expected_result_list) <= set(actual_result_list_sp):
                        pass_status = "是"
                        if expected_time:
                            if actual_time <= expected_time:
                                pass_status = "是"
                            else:
                                pass_status = "否"
                                fail_reason = "实际的响应时间大于预期的响应时间\n"
                                logger.error("实际的响应时间大于预期的响应时间")
                                if dingtalk_switch == "开":
                                    alarm_message = response_time_alarm(
                                        case_name, step_name, url,
                                        request_mode, body, headers,
                                        query_string, actual_time,
                                        expected_time)
                                    send_dingtalk_alarm(alarm_message)
                                    logger.info("钉钉报警发送成功")
                    else:
                        pass_status = "否"
                        fail_reason = "预期的响应结果与实际的响应结果断言失败\n"
                        logger.error("预期的响应结果与实际的响应结果断言失败")
                        if dingtalk_switch == "开":
                            alarm_message = response_result_alarm(
                                case_name, step_name, url, request_mode, body,
                                headers, query_string)
                            send_dingtalk_alarm(alarm_message)
                            logger.info("钉钉报警发送成功")
                else:
                    pass_status = "否"
                    fail_reason = "预期的响应代码与实际的响应代码不相等\n"
                    logger.error("预期的响应代码与实际的响应代码不相等")
                    if dingtalk_switch == "开":
                        alarm_message = response_code_alarm(
                            case_name, step_name, url, request_mode, body,
                            headers, query_string, expected_code, actual_code)
                        send_dingtalk_alarm(alarm_message)
                        logger.info("钉钉报警发送成功")

                RunningResults.objects.create(
                    running_results_step_id=step_id,
                    pass_status=pass_status,
                    fail_reason=fail_reason,
                    run_time=datetime.now(),
                    actual_time=actual_time,
                    actual_code=actual_code,
                    actual_result=actual_result_text,
                )

        logger.info("**********手动调试微服务结束**********\n")

    def update_button(self, obj):
        # 修改按钮
        button_html = '<a class="icon fa fa-edit" style="color: green" href="/admin/guard/microservice/%s/update/">修改</a>' % obj.id
        return format_html(button_html)

    update_button.short_description = '<span style="color: green">修改</span>'
    update_button.allow_tags = True

    def delete_button(self, obj):
        # 删除按钮
        button_html = '<a class="icon fa fa-times" style="color: blue" href="/admin/guard/microservice/%s/delete/">删除</a>' % obj.id
        return format_html(button_html)

    delete_button.short_description = '<span style="color: blue">删除</span>'
    delete_button.allow_tags = True

    form_layout = (
        Main(
            Fieldset('微服务信息部分', 'microservice_name', 'microservice_on_off',
                     'dingding_on_off', 'microservice_introduce'), ),
        # Side(
        #     Fieldset('时间部分',
        #              'create_time', 'update_time'),
        # )
    )

    list_display = [
        'id',
        'microservice_name',
        'microservice_on_off',
        'dingding_on_off',
        'case_total',
        'microservice_introduce',
        'create_time',
        'update_time',
        'debug_button',
        'update_button',
        'delete_button',
    ]
    ordering = ("id", )
    search_fields = ("microservice_name", )
    list_filter = ["create_time"]
    show_detail_fields = ['microservice_name']
    list_display_links = ('id', 'microservice_name')
    list_editable = ['microservice_name']
    list_per_page = 10

    batch_fields = (
        'microservice_name',
        'microservice_introduce',
    )
    # 可批量修改的字段
    actions = [CopyAction, BatchChangeAction]
Exemplo n.º 23
0
class BeautyMelodyNewsAdmin(RichTextAdmin):
    list_display = ('title_cn', 'title_en', 'publish_time')
    form_layout = (Main(Fieldset('图片与日期', 'img', 'publish_time'),
                        Fieldset('中文信息', 'title_cn', 'detail_cn'),
                        Fieldset('英文信息', 'title_en', 'detail_en')))
Exemplo n.º 24
0
class StepAdmin(object):
    model = Step
    extra = 1
    # 提供1个足够的选项行,也可以提供N个
    style = "accordion"

    # 折叠

    def save_models(self):
        # 重写保存方法
        obj = self.new_obj
        obj.api = re.sub("\s", "", obj.api)
        obj.body = re.sub("\s", "", obj.body)
        obj.headers = re.sub("\s", "", obj.headers)
        obj.query_string = re.sub("\s", "", obj.query_string)
        obj.expected_result = re.sub("\s", "", obj.expected_result)
        obj.regular = re.sub("\s", "", obj.regular)
        # 一次性去除空格、换行符、制表符
        self.new_obj.save()

    def step_case_foreign(self, obj):
        # 给外键添加颜色
        button_html = '<a style="color: red" href="/admin/guard/case/%s/detail/?_format=html">%s</a>' % (
            obj.step_case.id, obj.step_case)
        # %s(,)匹配多个
        return format_html(button_html)

    step_case_foreign.short_description = '<span style="color: red">用例名称</span>'
    step_case_foreign.allow_tags = True

    def running_total(self, obj):
        # 利用外键反向统计步骤总数
        button_html = '<span style="color: brown">%s</span>' % obj.running_key.all(
        ).count()
        return format_html(button_html)

    running_total.short_description = '<span style="color: brown">运行总数</span>'
    running_total.allow_tags = True

    def update_button(self, obj):
        # 修改按钮
        button_html = '<a class="icon fa fa-edit" style="color: green" href="/admin/guard/step/%s/update/">修改</a>' % obj.id
        return format_html(button_html)

    update_button.short_description = '<span style="color: green">修改</span>'
    update_button.allow_tags = True

    def delete_button(self, obj):
        # 删除按钮
        button_html = '<a class="icon fa fa-times" style="color: blue" href="/admin/guard/step/%s/delete/">删除</a>' % obj.id
        return format_html(button_html)

    delete_button.short_description = '<span style="color: blue">删除</span>'
    delete_button.allow_tags = True

    form_layout = (
        Main(
            Fieldset('步骤信息部分', 'step_case', 'step_name', 'request_mode', 'api',
                     'body', 'headers', 'query_string', 'expected_time',
                     'expected_code', 'expected_result', 'regular'), ),
        # Side(
        #     Fieldset('时间部分',
        #              'create_time', 'update_time'),
        # )
    )
    # 详情页面字段分区,请注意不是fieldsets

    list_display = [
        'id',
        'step_case_foreign',
        'step_name',
        'running_total',
        'request_mode',
        'api',
        'body',
        'headers',
        'query_string',
        'expected_time',
        'expected_code',
        'expected_result',
        'regular',
        'create_time',
        'update_time',
        'update_button',
        'delete_button',
    ]

    ordering = ("id", )
    search_fields = ("step_name", )
    list_filter = ["create_time"]
    list_display_links = ('id', 'step_case_foreign', 'step_name')
    show_detail_fields = ['step_name']
    list_editable = ['step_name']
    list_per_page = 10

    batch_fields = (
        'step_name',
        'request_mode',
        'api',
        'body',
        'headers',
        'query_string',
        'expected_time',
        'expected_code',
        'expected_result',
        'regular',
    )
    # 可批量修改的字段
    actions = [CopyAction, BatchChangeAction]
Exemplo n.º 25
0
class ContactUsAdmin(RichTextAdmin):
    form_layout = (Main(
        Fieldset('地图', 'img'),
        Fieldset('中文信息', 'title_cn', 'content_cn'),
        Fieldset('英文信息', 'title_en', 'content_en'),
    ))
Exemplo n.º 26
0
class RunningResultsAdmin(object):
    def has_add_permission(self):
        # 禁用增加按钮
        return False

    def case_foreign(self, obj):
        # 给外键添加颜色
        button_html = '<a style="color: orange" href="/admin/guard/case/%s/detail/?_format=html">%s</a>' % (
            obj.running_results_step.step_case.id,
            obj.running_results_step.step_case)
        # %s(,)匹配多个
        return format_html(button_html)

    case_foreign.short_description = '<span style="color: orange">用例名称</span>'
    case_foreign.allow_tags = True

    def running_step_foreign(self, obj):
        # 给外键添加颜色
        button_html = '<a style="color: red" href="/admin/guard/step/%s/detail/?_format=html">%s</a>' % (
            obj.running_results_step.id, obj.running_results_step)
        # %s(,)匹配多个
        return format_html(button_html)

    running_step_foreign.short_description = '<span style="color: red">步骤名称</span>'
    running_step_foreign.allow_tags = True

    def delete_button(self, obj):
        # 删除按钮
        button_html = '<a class="icon fa fa-times" style="color: blue" href="/admin/guard/runningresults/%s/delete/">删除</a>' % obj.id
        return format_html(button_html)

    delete_button.short_description = '<span style="color: blue">删除</span>'
    delete_button.allow_tags = True

    form_layout = (
        Main(
            Fieldset('运行结果部分', 'case_foreign', 'running_results_step',
                     'pass_status', 'fail_reason', 'run_time', 'actual_time',
                     'actual_code', 'actual_result'), ),
        # Side(
        #     Fieldset('时间部分',
        #              'create_time', 'update_time'),
        # )
    )

    list_display = [
        'id',
        'case_foreign',
        'running_step_foreign',
        'pass_status',
        'fail_reason',
        'run_time',
        'actual_time',
        'actual_code',
        'actual_result_ellipsis',
        'delete_button',
    ]
    ordering = ("-id", )
    search_fields = ['pass_status']
    list_display_links = None
    # 禁用编辑链接
    show_detail_fields = ['pass_status']
    readonly_fields = [
        'id', 'running_results_step', 'pass_status', 'fail_reason', 'run_time',
        'actual_time', 'actual_code', 'actual_result_ellipsis'
    ]
    # 设置只读字段
    list_per_page = 10
Exemplo n.º 27
0
class HostAdmin(object):
    def open_web(self, instance):
        return """<a href="http://%s" target="_blank">Open</a>""" % instance.ip

    open_web.short_description = "Acts"
    open_web.allow_tags = True
    open_web.is_column = True

    list_display = (
        "name",
        "idc",
        "host_group",
        "status",
        "info",
        "left",
        "description",
        "ip",
    )
    list_display_links = ("name", )

    raw_id_fields = ("idc", )
    style_fields = {"system": "radio-inline"}

    search_fields = ["name", "ip", "description"]
    list_filter = [
        "idc", "host_group", "cabinet", "guarantee_date", "status", "brand",
        "hard_disk", "memory", "left"
    ]

    list_quick_filter = [{"field": "idc__name", "limit": 10}]
    # list_quick_filter = ["idc_id"]
    list_bookmarks = [{
        "title": "Need Guarantee",
        "query": {
            "status_exact": 2
        },
        "order": ("guarantee_date", ),
        "cols": ("brand", "guarantee_date"),
    }]

    show_detail_fields = ("idc", )
    list_editable = ("name", "idc", "info", "description", "ip", "left")
    save_as = True

    aggregate_fields = {"guarantee_date": "min"}
    grid_layouts = ("table", "thumbnails")

    form_layout = (Main(
        TabHolder(
            Tab(
                "Comm Fields",
                Fieldset(
                    "Company data",
                    "name",
                    "idc",
                    "cabinet",
                    "address_number",
                    "ip",
                    "internal_ip",
                    "user",
                    "password",
                    "host_group",
                    "administrator",
                    "left",
                    "guarantee_date",
                    "system_user",
                    "system_password",
                    description="some comm fields, required",
                ), Inline(Port)),
            Tab(
                "Extend Fields",
                Fieldset(
                    "Contact details",
                    Row("brand", "model"),
                    Row("cpu"),
                    Row(AppendedText("hard_disk", "G"),
                        AppendedText("memory", "G")),
                ),
            ),
        ), ), Side(Fieldset("Status data", "status"), ))
    inlines = [PortInline]
    reversion_enable = True

    data_charts = {
        "host_service_type_counts": {
            'title': u"Host service type count",
            "x-field": "host_group",
            "y-field": ("host_group", ),
            "option": {
                "series": {
                    "bars": {
                        "align": "center",
                        "barWidth": 0.8,
                        'show': True
                    }
                },
                "xaxis": {
                    "aggregate": "count",
                    "mode": "categories"
                },
            },
        },
    }
Exemplo n.º 28
0
class ProductInfoAdmin(object):
    inlines = [ModuleInfoAdmin]

    # 使用内联显示

    def update_button(self, obj):
        # 修改按钮
        button_html = '<a class="icon fa fa-edit" style="color: green" href="/admin/interface/productinfo/%s/update/">修改</a>' % obj.id
        return format_html(button_html)

    update_button.short_description = '<span style="color: green">修改</span>'
    update_button.allow_tags = True

    def delete_button(self, obj):
        # 删除按钮
        button_html = '<a class="icon fa fa-times" style="color: blue" href="/admin/interface/productinfo/%s/delete/">删除</a>' % obj.id
        return format_html(button_html)

    delete_button.short_description = '<span style="color: blue">删除</span>'
    delete_button.allow_tags = True

    form_layout = (
        Main(
            Fieldset('产品信息部分',
                     'product_name', 'product_describe'),
            Fieldset('人员部分',
                     'product_manager', 'developer',
                     'tester'),
        ),
        # Side(
        #     Fieldset('时间部分',
        #              'create_time', 'update_time'),
        # )
    )
    # 详情页面字段分区

    list_display = [
        'id',
        'product_name',
        'product_describe',
        'product_manager',
        'developer',
        'tester',
        'module_sum',
        'create_time',
        'update_time',
        'update_button',
        'delete_button',
    ]

    ordering = ("id",)
    search_fields = ("product_name",)
    list_filter = ["product_manager", "create_time"]
    list_display_links = ('id', 'product_name')
    show_detail_fields = ['product_name']
    list_editable = ['product_name']
    list_per_page = 10

    import_export_args = {
        'import_resource_class': ProductInfoResource,
        # 'export_resource_class': ProductInfoResource,
    }
    # 列表页面,添加导入按钮
    list_export_fields = (
        'id',
        'product_name',
        'product_describe',
        'product_manager',
        'developer',
        'tester',
        'create_time'
    )
    # 列表页面,导出的字段

    batch_fields = (
        'product_name',
        'product_describe',
        'product_manager',
        'developer',
        'tester'
    )
    # 可批量修改的字段
    actions = [CopyAction, BatchChangeAction]
    # 列表页面,添加复制动作与批量修改动作

    list_bookmarks = [{
        "title": "产品书签",
        # 书签的名称
        "query": {"name": ""},
        # 过滤参数
        "order": ("-id",),
        # 排序
        "cols": (
            "product_name", "product_describe"),
        # 显示的列
        "search": "产品"
        # 搜索参数
    }]
Exemplo n.º 29
0
        'CertificateType',
        'RecipientsPlatform',
    )
    list_editable = ('SKU', 'WorkTitle', 'WorkClass', 'Status',
                     'RegistrationNo', 'CertificateType', 'RegistrationDate')
    show_detail_fields = ['id']
    fields = ('Source', 'SKU', 'WorkTitle', 'WorkClass', 'CopyrightArea',
              'CopyrightOwner', 'CompletionDate', 'CommitDate', 'Status',
              'RegistrationNo', 'RegistrationDate', 'CertificateType',
              'RecipientsPlatform', 'RecipientsShop', 'Inputer',
              'RecipientsPurpose', 'AttachmentUrl1', 'AttachmentUrl2')
    form_layout = (
        Fieldset(u'版权信息',
                 Row('Source', 'SKU', 'WorkTitle'),
                 Row('WorkClass', 'CopyrightArea', 'CopyrightOwner'),
                 Row('CompletionDate', 'CommitDate', 'Status'),
                 Row('RegistrationNo', 'RegistrationDate', 'CertificateType'),
                 Row('Inputer'),
                 Row('AttachmentUrl1', 'AttachmentUrl2'),
                 css_class='unsort '),
        Fieldset(u'领用信息',
                 Row('RecipientsPlatform', 'RecipientsShop'),
                 Row('RecipientsPurpose'),
                 css_class='unsort '),
    )

    def get_list_queryset(self):
        request = self.request
        qs = super(t_copyright_Admin, self).get_list_queryset()

        WorkClass = request.GET.get('WorkClass', '')
        CopyrightArea = request.GET.get('CopyrightArea', '')
Exemplo n.º 30
0
class not_clothing_salesman_registration_Admin(object):
    search_box_flag = True
    list_display = (
        'ThisMonth',
        'Category',
        'Department',
        'GroupLeader',
        'Salesperson',
        'FirstDay',
        'SecondDay',
        'ThirdDay',
        'FourthDay',
        'FifthDay',
        'SixthDay',
        'SeventhDay',
        'show_SumofFirstWeek',
        'EighthDay',
        'NinthDay',
        'TenthDay',
        'EleventhDay',
        'TwelfthDay',
        'ThirteenthDay',
        'FourteenthDay',
        'show_SumofSecondWeek',
        'FifteenthDay',
        'SixteenthDay',
        'SeventeenthDay',
        'EighteenthDay',
        'NineteenthDay',
        'TwentiethDay',
        'TwentyFirstDay',
        'show_SumofThirdWeek',
        'TwentySecondDay',
        'TwentyThirdDay',
        'TwentyFourthDay',
        'TwentyFifthDay',
        'TwentySixthDay',
        'TwentySeventhDay',
        'TwentyEighthDay',
        'show_SumofFourthWeek',
        'TwentyNinthDay',
        'ThirtiethDay',
        'ThirtiethFirstDay',
        'show_SumofMonth',
        'CompletionDegree',
        'UnfinishedCause',
    )

    list_editable = (
        'FirstDay',
        'SecondDay',
        'ThirdDay',
        'FourthDay',
        'FifthDay',
        'SixthDay',
        'SeventhDay',
        'EighthDay',
        'NinthDay',
        'TenthDay',
        'EleventhDay',
        'TwelfthDay',
        'ThirteenthDay',
        'FourteenthDay',
        'FifteenthDay',
        'SixteenthDay',
        'SeventeenthDay',
        'EighteenthDay',
        'NineteenthDay',
        'TwentiethDay',
        'TwentyFirstDay',
        'TwentySecondDay',
        'TwentyThirdDay',
        'TwentyFourthDay',
        'TwentyFifthDay',
        'TwentySixthDay',
        'TwentySeventhDay',
        'TwentyEighthDay',
        'TwentyNinthDay',
        'ThirtiethDay',
        'ThirtiethFirstDay',
        'CompletionDegree',
        'UnfinishedCause',
    )

    fields = (
        'ThisYear',
        'ThisMonth',
        'Category',
        'Department',
        'GroupLeader',
        'Salesperson',
    )

    form_layout = (Fieldset(u'基本信息',
                            Row(
                                'ThisYear',
                                'ThisMonth',
                                'Category',
                            ),
                            Row(
                                'Department',
                                'GroupLeader',
                                'Salesperson',
                            ),
                            css_class='unsort '), )

    def show_SumofFirstWeek(self, obj):
        SumofFirstWeek = 0
        rt = ''
        if obj.FirstDay is not None and str(obj.FirstDay).strip() != '':
            SumofFirstWeek += obj.FirstDay
        if obj.SecondDay is not None and str(obj.SecondDay).strip() != '':
            SumofFirstWeek += obj.SecondDay
        if obj.ThirdDay is not None and str(obj.ThirdDay).strip() != '':
            SumofFirstWeek += obj.ThirdDay
        if obj.FourthDay is not None and str(obj.FourthDay).strip() != '':
            SumofFirstWeek += obj.FourthDay
        if obj.FifthDay is not None and str(obj.FifthDay).strip() != '':
            SumofFirstWeek += obj.FifthDay
        if obj.SixthDay is not None and str(obj.SixthDay).strip() != '':
            SumofFirstWeek += obj.SixthDay
        if obj.SeventhDay is not None and str(obj.SeventhDay).strip() != '':
            SumofFirstWeek += obj.SeventhDay

        obj.SumofFirstWeek = SumofFirstWeek
        obj.save()

        rt = "%s%s" % (rt, obj.SumofFirstWeek)

        return mark_safe(rt)

    show_SumofFirstWeek.short_description = u'第一周<br>小计'

    def show_SumofSecondWeek(self, obj):
        SumofSecondWeek = 0
        rt = ''
        if obj.EighthDay is not None and str(obj.EighthDay).strip() != '':
            SumofSecondWeek += obj.EighthDay
        if obj.NinthDay is not None and str(obj.NinthDay).strip() != '':
            SumofSecondWeek += obj.NinthDay
        if obj.TenthDay is not None and str(obj.TenthDay).strip() != '':
            SumofSecondWeek += obj.TenthDay
        if obj.EleventhDay is not None and str(obj.EleventhDay).strip() != '':
            SumofSecondWeek += obj.EleventhDay
        if obj.TwelfthDay is not None and str(obj.TwelfthDay).strip() != '':
            SumofSecondWeek += obj.TwelfthDay
        if obj.ThirteenthDay is not None and str(
                obj.ThirteenthDay).strip() != '':
            SumofSecondWeek += obj.ThirteenthDay
        if obj.FourteenthDay is not None and str(
                obj.FourteenthDay).strip() != '':
            SumofSecondWeek += obj.FourteenthDay

        obj.SumofSecondWeek = SumofSecondWeek

        rt = "%s%s" % (rt, obj.SumofSecondWeek)
        obj.save()

        return mark_safe(rt)

    show_SumofSecondWeek.short_description = u'第二周<br>小计'

    def show_SumofThirdWeek(self, obj):
        SumofThirdWeek = 0
        rt = ''
        if obj.FifteenthDay is not None and str(
                obj.FifteenthDay).strip() != '':
            SumofThirdWeek += obj.FifteenthDay
        if obj.SixteenthDay is not None and str(
                obj.SixteenthDay).strip() != '':
            SumofThirdWeek += obj.SixteenthDay
        if obj.SeventeenthDay is not None and str(
                obj.SeventeenthDay).strip() != '':
            SumofThirdWeek += obj.SeventeenthDay
        if obj.EighteenthDay is not None and str(
                obj.EighteenthDay).strip() != '':
            SumofThirdWeek += obj.EighteenthDay
        if obj.NineteenthDay is not None and str(
                obj.NineteenthDay).strip() != '':
            SumofThirdWeek += obj.NineteenthDay
        if obj.TwentiethDay is not None and str(
                obj.TwentiethDay).strip() != '':
            SumofThirdWeek += obj.TwentiethDay
        if obj.TwentyFirstDay is not None and str(
                obj.TwentyFirstDay).strip() != '':
            SumofThirdWeek += obj.TwentyFirstDay

        obj.SumofThirdWeek = SumofThirdWeek
        obj.save()
        rt = "%s%s" % (rt, obj.SumofThirdWeek)

        return mark_safe(rt)

    show_SumofThirdWeek.short_description = u'第三周<br>小计'

    def show_SumofFourthWeek(self, obj):
        SumofFourthWeek = 0
        rt = ''
        if obj.TwentySecondDay is not None and str(
                obj.TwentySecondDay).strip() != '':
            SumofFourthWeek += obj.TwentySecondDay
        if obj.TwentyThirdDay is not None and str(
                obj.TwentyThirdDay).strip() != '':
            SumofFourthWeek += obj.TwentyThirdDay
        if obj.TwentyFourthDay is not None and str(
                obj.TwentyFourthDay).strip() != '':
            SumofFourthWeek += obj.TwentyFourthDay
        if obj.TwentyFifthDay is not None and str(
                obj.TwentyFifthDay).strip() != '':
            SumofFourthWeek += obj.TwentyFifthDay
        if obj.TwentySixthDay is not None and str(obj.FirstDay).strip() != '':
            SumofFourthWeek += obj.TwentySixthDay
        if obj.TwentySeventhDay is not None and str(
                obj.TwentySeventhDay).strip() != '':
            SumofFourthWeek += obj.TwentySeventhDay
        if obj.TwentyEighthDay is not None and str(
                obj.TwentyEighthDay).strip() != '':
            SumofFourthWeek += obj.TwentyEighthDay

        obj.SumofFourthWeek = SumofFourthWeek
        obj.save()

        rt = "%s%s" % (rt, obj.SumofFourthWeek)

        return mark_safe(rt)

    show_SumofFourthWeek.short_description = u'第四周<br>小计'

    def show_SumofMonth(self, obj):
        SumofMonth = 0
        rt = ''
        if obj.TwentyNinthDay is not None and str(
                obj.TwentyNinthDay).strip() != '':
            SumofMonth += obj.TwentyNinthDay
        if obj.ThirtiethDay is not None and str(
                obj.ThirtiethDay).strip() != '':
            SumofMonth += obj.ThirtiethDay
        if obj.ThirtiethFirstDay is not None and str(
                obj.ThirtiethFirstDay).strip() != '':
            SumofMonth += obj.ThirtiethFirstDay

        SumofMonth += obj.SumofFirstWeek + obj.SumofSecondWeek + obj.SumofThirdWeek + obj.SumofFourthWeek
        obj.SumofMonth = SumofMonth

        rt = "%s%s" % (rt, obj.SumofMonth)
        obj.save()

        return mark_safe(rt)

    show_SumofMonth.short_description = u'月总和'

    def save_models(self):
        obj = self.new_obj
        try:
            obj.save()
        except:
            messages.error(self.request, '添加失败!这条记录已存在!')

    def get_list_queryset(self):
        request = self.request
        qs = super(not_clothing_salesman_registration_Admin,
                   self).get_list_queryset()

        ThisYear = request.GET.get('ThisYear', '')
        ThisMonth = request.GET.get('ThisMonth', '')
        Category = request.GET.get('Category', '')
        Department = request.GET.get('Department', '')
        GroupLeader = request.GET.get('GroupLeader', '')
        Salesperson = request.GET.get('Salesperson', '')

        SumofMonthStart = request.GET.get('SumofMonthStart', '')
        SumofMonthEnd = request.GET.get('SumofMonthEnd', '')

        searchList = {
            'ThisYear__exact': ThisYear,
            'ThisMonth__exact': ThisMonth,
            'Category__exact': Category,
            'Department__exact': Department,
            'GroupLeader__exact': GroupLeader,
            'Salesperson__exact': Salesperson,
            'SumofMonth__gte': SumofMonthStart,
            'SumofMonth__lt': SumofMonthEnd,
        }
        sl = {}
        for k, v in searchList.items():
            if isinstance(v, list):
                if v:
                    sl[k] = v
            else:
                if v is not None and v.strip() != '':
                    # if k == 'ShopName__exact':
                    #  v = 'Wish-' + v.zfill(4)
                    # messages.error(request, v)
                    sl[k] = v
        if sl is not None:
            # messages.error(request, sl)
            try:
                qs = qs.filter(**sl)
            except Exception, ex:
                messages.error(request, u'输入的查询数据有问题!')

        return qs