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

Django商品详情页尺寸下拉菜单显示商品名而非尺寸,求解决

商品变体尺寸下拉菜单显示错误的修复方案

问题现状

商品详情页的尺寸下拉菜单显示商品名称而非尺寸选项,需修复该问题以确保尺寸变体能正确展示。

问题原因

当前模板中颜色和尺寸下拉菜单均直接遍历single_product.variation_set.all,未区分变体分类(颜色/尺寸),导致所有类型的变体都被加载显示;同时未利用模型中定义的VariationManager来筛选特定类别的变体。

修复步骤

1. 更新视图函数,传递筛选后的变体数据

在商品详情视图中,使用VariationManager提供的sizes()和colors()方法,分别获取当前商品的颜色和尺寸变体,传递到模板:

from django.shortcuts import render, get_object_or_404
from .models import Product, Variation

def product_detail(request, category_slug, product_slug):
    single_product = get_object_or_404(Product, category__slug=category_slug, slug=product_slug)
    # 获取激活的颜色变体
    colors = Variation.objects.colors().filter(product=single_product)
    # 获取激活的尺寸变体
    sizes = Variation.objects.sizes().filter(product=single_product)
    
    context = {
        'single_product': single_product,
        'colors': colors,
        'sizes': sizes,
        # 保留原有其他上下文数据,比如in_cart等
    }
    return render(request, 'product-details.html', context)

2. 修改模板,分别渲染对应类别的变体

更新product-details.html中的下拉菜单代码,分别使用筛选后的colors和sizes数据:

颜色下拉菜单修改:

<div class="item-option-select">
    <h6>Choose Color</h6>
    <select name="color" class="form-control" required>
        <option value="" disabled selected>Select</option>
        {% for color in colors %}
        <option value="{{ color.variation_value }}">{{ color.variation_value }}</option>
        {% endfor %}
    </select>
</div>

尺寸下拉菜单修改:

<div class="item-option-select">
    <h6>Select Size</h6>
    <select name="size" class="form-control">
        <option value="" disabled selected>Select</option>
        {% for size in sizes %}
        <option value="{{ size.variation_value | lower }}">{{ size.variation_value | capfirst }}</option>
        {% endfor %}
    </select>
</div>

3. 验证数据库数据

确保后台添加的Variation数据中:

  • variation_category字段正确设置为size或color
  • is_active字段勾选为True(因为VariationManager默认只筛选激活的变体)

内容的提问来源于stack exchange,提问作者Md Nazmul Hossain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:17:05