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

使用ModelChoiceField时如何解决「选择有效选项,该选项不在可选范围内」错误?

问题

在Django模板中手动渲染select字段选项后,提交表单时触发错误:「请选择有效选项,该选项不在可选范围内」,同时错误提示要求填写必填字段,但我已完成所有必填项的填写。


相关代码

locations/models.py

class Location(models.Model):
    name = models.CharField(max_length=20)
    is_source = models.BooleanField(default=False)  # 是否为发货地
    is_destination = models.BooleanField(default=False)  # 是否为收货地

    def __str__(self):
        return self.name

orders/models.py

class Order(models.Model):
    order_number = models.IntegerField(unique=True)  # 订单编号(唯一)
    order_date = models.DateField(auto_now_add=True)  # 订单创建日期(自动生成)
    type = models.CharField(max_length=15, choices=TYPES)  # 订单类型
    source = models.ForeignKey(Location, default=1, on_delete=models.SET_DEFAULT, related_name='ordered_here')  # 发货地关联
    destination = models.ForeignKey(Location, default=1, on_delete=models.SET_DEFAULT, related_name='delivered_here')  # 收货地关联
    items = models.TextField()  # 物品清单
    assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='orders_to_serve')  # 指派处理人
    customer = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='orders_made')  # 下单用户
    status = models.CharField(max_length=15, choices=STATUSES)  # 订单状态

orders/forms.py

class OrderForm(ModelForm):
    source = forms.ModelChoiceField(queryset=Location.objects.filter(is_source=True))  # 仅筛选可作为发货地的地点
    destination = forms.ModelChoiceField(queryset=Location.objects.filter(is_destination=True))  # 仅筛选可作为收货地的地点

    class Meta:
        model = Order
        fields = ['source', 'destination', 'items']

    def save(self, commit=True):
        instance = super().save(commit=False)
        instance.order_number = math.floor(time.time())  # 用时间戳生成订单号
        instance.type = 'Purchase'  # 设置订单类型为采购
        instance.customer = self.context.get('request').user  # 关联当前下单用户
        instance.status = 'New'  # 设置订单状态为新建
        if commit:
            instance.save()

        return instance

orders/create.html

<form class="" method="POST">
    {% csrf_token %}
    <h1 class='text-center'>创建订单</h1>
    <div class='row'>
        <div class='col-md-6 px-2'>
            <span class="fw-bold mx-2">发货地</span>
            <div class="control-container  border-primary d-flex align-items-center">
                <i class="fa fa-map"></i>
                <select class="control ms-1 flex-grow-1" name="{{form.source.html_name}}" required>
                    {% for value,label in form.source.field.choices %}
                    <option value="{{value}}">{{label}}</option>
                    {% endfor %}
                </select>
            </div>
        </div>
        <div class='col-md-6 px-2'>
            <span class="fw-bold mx-2">收货地</span>
            <div class="control-container  border-primary d-flex align-items-center">
                <i class="fa fa-map"></i>
                <select class="control ms-1 flex-grow-1" name="{{form.destination.html_name}}" required>
                    {% for value,label in form.destination.field.choices %}
                    <option value="{{value}}">{{label}}</option>
                    {% endfor %}
                </select>
            </div>
        </div>
    </div>
    <div class='row'>
        <div class='col-12 px-2'>
            <span class="fw-bold mx-2">物品清单(示例:2个 Luxaire 双人床垫)</span>
            <div class="control-container  border-primary d-flex align-items-center">
                <textarea class="control ms-1 flex-grow-1" rows="10" name="{{form.items.html_name}}" placeholder='示例:2个 Luxaire 双人床垫' required></textarea>
            </div>
        </div>
    </div>
    <button type="submit" class="btn btn-primary w-100">提交订单</button>
</form>

orders/views.py

class OrderUpdateView(generic.edit.UpdateView):
    model = Order
    template_name = 'orders/update.html'
    context_object_name = 'order'
    form_class = OrderForm

内容的提问来源于stack exchange,提问作者Nceku Moyo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:05:38