You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django:库存表单选中商品时如何显示对应关联单位

解决方案

要实现选中商品后实时显示对应单位,核心是把商品关联的单位数据传递到前端,再通过JavaScript监听选择框变化动态更新显示。下面提供两种实用实现方式:

方法一:将单位数据嵌入下拉选项(无需额外请求)

1. 调整表单代码,注入单位数据

修改forms.py,给商品下拉框的每个选项添加存储单位的自定义属性:

from django import forms
from .models import Stock, Items

class StockForm(forms.ModelForm):
    class Meta:
        model = Stock
        fields = ['item']
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 重新构建选项,把单位数据存入选项的data属性
        updated_choices = []
        for item in Items.objects.all():
            unit_name = item.units.name if item.units else ''
            updated_choices.append(
                (item.id, item.name, {'data-unit': unit_name})
            )
        self.fields['item'].widget.choices = updated_choices

2. 修改模板,添加前端监听逻辑

<div class="col-md-4 pl-0">
    {{ formsingle.item|as_crispy_field }}
</div>

<div class="col-md-1 p-0">
    <span id="unit-display"></span>
</div>

<script>
// 获取页面元素
const itemSelect = document.getElementById('id_item');
const unitDisplay = document.getElementById('unit-display');

// 页面加载时,若已有选中项则显示对应单位
if (itemSelect.value) {
    const selectedOption = itemSelect.options[itemSelect.selectedIndex];
    unitDisplay.textContent = selectedOption.dataset.unit || '';
}

// 监听选择框变化事件
itemSelect.addEventListener('change', function() {
    const selectedOption = this.options[this.selectedIndex];
    unitDisplay.textContent = selectedOption.dataset.unit || '';
});
</script>

方法二:通过AJAX请求后端获取单位数据

1. 添加后端接口

配置urls.py

from django.urls import path
from . import views

urlpatterns = [
    # 其他路由...
    path('get-item-unit/<int:item_id>/', views.get_item_unit, name='get_item_unit'),
]

编写views.py接口逻辑

from django.http import JsonResponse
from .models import Items

def get_item_unit(request, item_id):
    try:
        item = Items.objects.get(id=item_id)
        unit_name = item.units.name if item.units else ''
        return JsonResponse({'unit': unit_name})
    except Items.DoesNotExist:
        return JsonResponse({'unit': ''})

2. 模板中添加AJAX调用逻辑

<div class="col-md-4 pl-0">
    {{ formsingle.item|as_crispy_field }}
</div>

<div class="col-md-1 p-0">
    <span id="unit-display"></span>
</div>

<script>
const itemSelect = document.getElementById('id_item');
const unitDisplay = document.getElementById('unit-display');

// 初始加载时显示已选商品的单位
if (itemSelect.value) {
    fetchUnit(itemSelect.value);
}

// 监听选择变化
itemSelect.addEventListener('change', function() {
    fetchUnit(this.value);
});

// 发送AJAX请求获取单位
function fetchUnit(itemId) {
    if (!itemId) {
        unitDisplay.textContent = '';
        return;
    }
    fetch(`/get-item-unit/${itemId}/`)
        .then(response => response.json())
        .then(data => {
            unitDisplay.textContent = data.unit || '';
        })
        .catch(() => {
            unitDisplay.textContent = '';
        });
}
</script>

内容的提问来源于stack exchange,提问作者Amrita Stha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 20:01:04