2012-04-11 15 views
1

{{ form.creator }}ためDjangoは、このような<select>タグレンダリングするので、私は、(creatorという名前)フィールドの一つがForeignKeyあるModelFormを持っている:手動でDjangoのModelFormから選択フィールドを作成するには?

<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', 
     ) 

答えて

1

ModelChoiceField documentationは、これを行う方法について説明します。

が空のラベルを変更するには:あなたの2番目の問合せについては

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) 

を、それはまた、ドキュメントで説明されています。

最後に
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引数を使用します選択ウィジェット(これはModelFormフィールドで使用されているもの)のためのものです。上記のあなたの `creator`例えば、私は` OrderCreateForm`でfields`を ``からcreator`を削除し、あなたを追加する必要がありますので、

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

:最後に

、あなたはこのような何かを持っている必要があります'creator = MyCustomField(...)'のコード行?あるいは、 'クラスメータ'の下で 'フィールド 'にリストの一部として'作成者'を残していますか? – hobbes3

+1

カスタムフィールドでレンダリングしているので、削除する必要があります。 –

+0

'User'に依存するより複雑な' creator'リストが必要だったので、 '