如何从Django中的ModelForm手动创建一个select字段?

2024-07-05 09:01:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个ModelForm,其中一个字段(名为creator)是一个ForeignKey,因此对于{{ form.creator }}Django呈现{}标记,如下所示:

<select id="id_approver" name="approver">
    <option selected="selected" value="">---------</option>
    <option value="1">hobbes3</option>
    <option value="2">tareqmd</option>
    <option value="3">bob</option>
    <option value="4">sam</option>
    <option value="5">jane</option>
</select>

但是我想添加一个onchange事件属性,这样我可以在以后使用AJAX做其他事情。我还想将---------改成其他内容,并显示审批者的全名,而不是用户名。在

那么,是否有可能获得一个可能的审批者列表并生成我自己的选择选项?有点像

^{pr2}$

我也在想,大多数审批者的列表太大了(比如超过50个),那么我最终会想要一个可搜索的自动完成字段。所以我一定要自己写。在

如果有人需要,我的ModelForm如下所示:

class OrderCreateForm( ModelForm ) :
    class Meta :
        model = Order
        fields = (
            'creator',
            'approver',
            'work_type',
            'comment',
        )

Tags: djangoname标记formid列表valueselect
1条回答
网友
1楼 · 发布于 2024-07-05 09:01:22

ModelChoiceField documentation说明了如何执行此操作。在

要更改空标签:

empty_label

    By default the <select> widget used by ModelChoiceField
    will have an empty choice at the top of the list. You can change the text
    of this label (which is "    -" by default) with the empty_label
    attribute, or you can disable the empty label entirely by setting
    empty_label to None:

    # A custom empty label
    field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")

    # No empty label
    field2 = forms.ModelChoiceField(queryset=..., empty_label=None)

关于您的第二个查询,请参见文档中的说明:

^{pr2}$

最后,要传递一些自定义ajax,请使用select小部件的^{}参数(这是在ModelForm字段中使用的参数)。在

最后,你应该有这样的东西:

creator = MyCustomField(queryset=...,
                        empty_label="Please select",
                        widget=forms.Select(attrs={'onchange':'some_ajax_function()'})

相关问题 更多 >