2

フィールドのModelForm1 つ ( という名前creator) が であるForeignKeyため、{{ form.creator }}Django の場合、<select>タグは次のようにレンダリングされます。

<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 を使用して別のことを実行できるようにしたいと考えています。---------また、別のことを言い、承認者のユーザー名ではなくフルネームを表示するように変更したいと考えています。

可能な承認者のリストを取得して、独自の選択オプションを生成することは可能ですか? みたいな

<select id="id_approver" name="approver" onchange="some_ajax_function()">
    <option select="selected" value="0">Choose a user</option>
{% for approver in form.approver.all %} <!-- This won't work -->
    <option value="{{ approver.pk }}">{{ approver.get_full_name }}</option>
{% endfor %}
</select>

また、承認者のリストのほとんどが大きくなりすぎる (50 を超えるなど) と考えているので、最終的には、承認者のために何らかの検索可能なオートコンプリート フィールドが必要になるでしょう。そのため、必ず独自の HTML を作成する必要があります。

誰かがそれを必要とする場合に備えて、私のModelForm見た目は次のようになります。

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

1 に答える 1

1

ModelChoiceFieldのドキュメントでは、これを行う方法について説明しています。

空のラベルを変更するには:

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)

2番目のクエリについては、ドキュメントでも説明されています:

The __unicode__ method of the model will be called to generate string
representations of the objects for use in the field's choices;
to provide customized representations, subclass ModelChoiceField and override
label_from_instance. This method will receive a model object, and should return
a string suitable for representing it. For example:

class MyModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "My Object #%i" % obj.id

最後に、いくつかのカスタム ajax を渡すにattrsは、select ウィジェットの引数を使用します (これは ModelForm フィールドで使用されます)。

最終的には、次のようになります。

creator = MyCustomField(queryset=...,
                        empty_label="Please select",
                        widget=forms.Select(attrs={'onchange':'some_ajax_function()'})
于 2012-04-11T05:10:35.460 に答える