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
  • 相关阅读:
    asp.net mvc4 webapi request获取参数
    各种加密和解密算法的实现
    SQL 排序的简单用法
    aiofiles拆分大文件
    21.11.16模拟 学校
    P3178 [HAOI2015]树上操作
    21.11.16模拟 bzoj3306树
    SP1557 GSS2 Can you answer these queries II
    21.11.16模拟 问题
    21.11.16模拟 真菌
  • 原文地址:https://www.cnblogs.com/canghai1024/p/13093928.html
Copyright © 2011-2022 走看看