使用来自 postgres arrayfield 的值在 django 视图中呈现下拉列表

Render dropdown in django view using values from postgres arrayfield

以下是模型中的示例:

class Shipment(models.Model):
    shipment_id = models.BigAutoField(null=False, primary_key=True)
    potential_shipping_dates = ArrayField(models.DateField(), verbose_name='Ship Dates', null=True)

以下是我在我的表格中尝试的内容:

class ShippingForm(forms.Form):
    potential_shipping_dates = forms.ModelChoiceField(queryset=Shipment.objects.all())
    def __init__(self, *args, **kwargs):
        super(ShippingForm, self).__init__(*args, **kwargs)

这里是我的表单添加到上下文的地方:

context['shippingForm'] = ShippingForm(initial=??what_goes_here_maybe??)

我的表单呈现良好,但我想显示一个下拉列表,每个选项都有一个日期。

好的,这有点复杂,但我想我明白你想做什么,以及你哪里出错了。

所以你有一个 Shipment 模型,每个 Shipment 实例都有一个字段,其中包含一些不同的 potential_shipping_dates

假设您有 2 批货物:

IN : ship1 = Shipment.objects.first()
OUT:

IN : ship1.potential_shipping_dates
OUT: ['01/01/2021', '02/02/2021']

IN : ship2 = Shipment.objects.last()
OUT:

IN : ship2.potential_shipping_dates
OUT: ['03/03/2021', '04/04/2021']

现在,您是否希望下拉列表包含所有 4 个可能的日期,这将 select Shipment

或者您想 select 在 select 发送表格中的货件之后的日期?

^^ 已在评论中回复

好的,您需要将实例传递给表单:

views.py

# Inherit from Django's UpdateView to have `instance` passed through to the form
class ShippingFormView(UpdateView):
    model = Shipment
    form_class = ShippingForm


# Or if you don't want to inherit from inherit from UpdateView
class ShippingFormView(Blah):
    model = Shipment
    form_class = ShippingForm

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['instance'] = self.get_object()
        return kwargs


# Or if you're using function based views
def shipping_form_view(request, pk):
    shipment = get_object_or_404(Shipment, pk=pk)
    form = ShippingForm(request, instance=shipment)
    ...

forms.py

class ShippingForm(forms.Form):
    potential_shipping_dates = forms.ChoiceField(choices=[])

    def __init__(self, *args, instance, **kwargs):
        super(ShippingForm, self).__init__(*args, **kwargs)
        self.fields['potential_shipping_dates'].choices = ((dt, dt) for dt in instance.potential_shipping_dates)

ModelChoiceFields 在 selecting 一个 object 时使用,而不是一个属性。