1

내가 (creator 이름) 분야의 ModelForm 곳 하나를 가지고하는 것은 장고는이 같은 <select> 태그 렌더링 {{ form.creator }}에 대한 있도록하는 ForeignKey입니다 :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이 작업을 수행하는 방법에 대해 설명합니다.

가 빈 라벨을 변경하려면 : 두 번째 질문에 대해서는

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 

, 일부 사용자 지정 아약스를 통과하려면 attrs 인수를 사용 (ModelForm 필드에서 사용되는) 선택 위젯의 경우. 결국

, 당신은 다음과 같이해야한다 : 나는 OrderCreateForm``에 fields``에서`creator`를 제거하고 추가해야합니다, 위의`creator` 그래서 예를 들면

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

당신의 'creator = MyCustomField (...)'에 대한 코드 줄? 아니면 '클래스 메타'에서 '필드'에 목록의 일부로 '작성자'를 유지합니까? – hobbes3

+1

사용자 지정 필드로 렌더링하므로 제거해야합니다. –

+0

'User'에 의존하는 좀 더 복잡한'creator'리스트가 필요했기 때문에''과'

관련 문제