【问题标题】:Django admin: How to show calculated value from entered values dynamically in Django admin form page?Django admin:如何在 Django 管理表单页面中动态显示输入值的计算值?
【发布时间】:2020-07-11 17:51:00
【问题描述】:

我有一个包含“价格”、“税”和“折扣”字段 (IntegerFields) 的表单。 然后会有一个名为“total_price”的只读字段。

当我们输入“价格”、“折扣”和“税”时,应自动显示“总价格”值。如果我们更改“折扣”或“价格”,那么“总价格”也会立即更改。

看到最终价格后,我们可以点击“保存”按钮。

如何在 Django admin 中实现这一点?

【问题讨论】:

    标签: django django-models django-admin django-admin-actions


    【解决方案1】:

    为此,您必须将自定义 Javascript 代码添加到您的管理页面。

    您可以这样做:

    1. 向管理员添加只读字段 - 它将显示“total_price”
    2. 将自定义脚本添加到管理页面。
    3. 编写 JS 脚本 - 该脚本将“实时更新”总价

    您的管理员可能如下所示:

    @admin.register(YourModel)
    class YourModelAdmin(admin.ModelAdmin):
    
        # some code here...
    
        readonly_fields = ('total_price', )
    
        def total_price(self, obj):
            # return whatever initial value you want
            return obj.price - obj.price*obj.discount
    
        # This is important - adding custom script to admin page
        @property
        def media(self):
            media = super().media
            media._js.append('js/your-custom-script.js')
            return media
    

    记住js/your-custom-script.js 必须在您的静态文件夹中。

    更新: 您可以使用 Meta 嵌套类来包含您的 JS,而不是覆盖 media 属性:

    class YourModelAdmin(admin.ModelAdmin):
        ...
        class Media:
            js = (
                'path-to-your-static-script-file.js',
            )
    

    最后一步是编写一个脚本来更新total_price 字段的值,只要其他字段发生更改。

    示例:如果您想在更改 price 时更改 total_price,您的脚本可以如下所示:

    if (!$) {
        $ = django.jQuery;
    }
    $(document).ready(function(){
        // Add event listener to "price" input
        $("#id_price").change(function(e){
            // Get entered value
            let price = parseFloat($(this).val());
    
            // Get discount value from another field 
            let discount = parseFloat($("#id_discount").val())
    
            // Compute total price in whatever way you want
            let total_price = price - price*discount;
    
            // Set value in read-only "total_price" field.
            $("div.field-total_price").find("div.readonly").text(total_price);
        });
    })
    

    如果您想在 discounttax 字段更改时更新 total_price,只需向它们添加事件侦听器即可。

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 1970-01-01
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      • 2023-01-06
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      相关资源
      最近更新 更多