繁体   English   中英

为什么 Django 表单选择字段不显示所选模型的初始值

[英]Why Django form choice field don't showing initial value from model as selected

无法将模型值表示为在表单选择字段中选择。 在模板中,我的对象有编辑选项,我想在表单字段中填充所有当前对象值,但选择的字段总是会显示模型默认值。 知道如何解决这个想法 django 功能吗?

所以我现在所拥有的:首先是我的模型:

class ClientPriceSelection(models.Model):
    A_B_choice = (
        (50.00, 50.00),
        (25.00, 25.00)
    )
    ...
    p_four = models.DecimalField(
        choices=A_B_choice, max_digits=6, decimal_places=2,
        default=50.00, verbose_name="...", help_text="(---)")

我的看法:

    addon = get_object_or_404(ClientPriceSelection, id=addon_id)
    # print(addon.p_four)
    form = ClientPriceListSelectionForm(
        request.POST or None,
        initial={
            'p_one': addon.p_one, 'p_two': addon.p_two,
            'p_three': addon.p_three, 'p_four': addon.p_four,
            'p_five': addon.p_five, 'p_seven': addon.p_seven,
            'p_eight': addon.p_eight, 'p_nine': addon.p_nine,
            'p_ten': addon.p_ten, 'p_eleven': addon.p_eleven,
            'internal_notes': addon.internal_notes,
        })
    context = {
        "form": form,
        'client': get_object_or_404(Client, id=addon.agreement.client.id),
    }

我的表格:

class ClientPriceListSelectionForm(forms.ModelForm):
    class Meta:
        model = ClientPriceSelection
        fields = [
            'p_one', 'p_two', 'p_three', 'p_four', 'p_five',
            'p_seven', 'p_eight', 'p_nine', 'p_ten', 'p_eleven',
            'internal_notes',
        ]
        widgets = {
            'internal_notes': forms.Textarea(
                attrs={'class': 'vLargeTextField', 'cols': '40', 'rows': '10', 'maxlength': '500'}),
        }

好的,我想通了,对于通过将初始值设置为表单来努力将选项标记为选择的任何人,请使用选择字段显示选项

initial={'your_field': object.get_yourField_display}

在我的情况下:

'p_four': addon.get_p_four_display,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM