zoukankan      html  css  js  c++  java
  • django的save_model和delete_model修改admin后台修改数据时的行为

    需求背景:

    当在admin后台修改数据时,重新执行celery异步任务生成首页静态页面

    异步任务代码如下:

    @shared_task(name='celery_tasks.generate_static_index')
    def generate_static_index():
        """生成首页静态页面"""
        # 获取商品分类信息
        goods_types = GoodsType.objects.all()
        # 获取轮播图信息
        goods_banners = IndexGoodsBanner.objects.all().order_by('index')  # 默认升序排列,如果降序则为"-index"
        # 获取促销活动信息
        promotion_banners = IndexPromotionBanner.objects.all().order_by('index')
        # 获取首页分类商品展示信息
        for type in goods_types:
            # 获取type种类首页展示的商品的图片信息
            image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1)
            # 获取type种类首页展示的商品的文字信息
            title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0)
    
            # 动态给type对象添加商品图片、文字信息
            type.image_banners = image_banners
            type.title_banners = title_banners
    
        # 组织模板上下文信息
        context = {
            'goods_types': goods_types,
            'goods_banners': goods_banners,
            'promotion_banners': promotion_banners,
    
        }
        #生成静态文件
        static_index_html = render_to_string('static_index.html',context=context)
        static_index_path = os.path.join(settings.BASE_DIR,'static/index.html')
        #将静态文件存储到static目录下
        with open(static_index_path,'w',encoding='utf-8') as f:
            f.write(static_index_html)
    View Code

    admin中代码如下:

    from django.contrib import admin
    from .models import GoodsType,IndexGoodsBanner,GoodsSKU,Goods,IndexPromotionBanner,IndexTypeGoodsBanner
    
    
    class BaseModelAdmin1(admin.ModelAdmin):
        """"""
        def save_model(self, request, obj, form, change):
            """新增或者更新数据时调用"""
            super().save_model(request,obj,form,change)
            from celery_tasks.tasks import generate_static_index
            print('开始执行任务')
            generate_static_index.delay()
    
        def delete_model(self, request, obj):
            """删除数据时调用"""
            super().delete_model(request,obj)
            from celery_tasks.tasks import generate_static_index
            generate_static_index.delay()
    
    class IndexPromotionBannerAdmin(BaseModelAdmin1):
        pass
    
    admin.site.register(IndexPromotionBanner,IndexPromotionBannerAdmin)
    View Code
  • 相关阅读:
    【洛谷4725】【模板】多项式对数函数(多项式 ln)
    【洛谷4516】[JSOI2018] 潜入行动(树上背包)
    【洛谷4463】[集训队互测2012] calc(动态规划+拉格朗日插值)
    【洛谷1973】[NOI2011] NOI 嘉年华(DP)
    【BZOJ2958】序列染色(动态规划)
    【CF1037H】Security(后缀自动机+线段树合并)
    【洛谷5308】[COCI2019] Quiz(WQS二分+斜率优化DP)
    【BZOJ3512】DZY Loves Math IV(杜教筛)
    【洛谷2178】[NOI2015] 品酒大会(后缀数组+单调栈)
    【BZOJ2878】[NOI2012] 迷失游乐园(基环树DP)
  • 原文地址:https://www.cnblogs.com/canghai1024/p/13093928.html
Copyright © 2011-2022 走看看