2014-02-21 45 views

回答

1

我想你正在修改模型窗體中使用的小部件。這是很好的文件here。不過,這裏有一個快速示例,應該是您要查找的內容。

class ExampleForm(forms.ModelForm): 
    field_1 = forms.CharField(widget=forms.SelectMultiple(choices=FIELD_1_CHOICES)) 
    field_2 = forms.CharField(widget=forms.SelectMultiple(choices=FIELD_2_CHOICES)) 
    field_3 = forms.CharField(widget=forms.SelectMultiple(choices=FIELD_3_CHOICES)) 
    field_4 = forms.CharField(widget=forms.TextInput()) 

    class Meta: 
     model = ExampleModel 
     fields = ['field_1', 'field_2', 'field_3', 'field_4'] 

您需要爲每個字段定義FIELD_1_CHOICES,併爲您提供任何選項。此外,您不必爲field_4執行該行,因爲TextInputCharField的默認小部件,但我將其添加爲明確。

1

你可以使用這個自定義小部件來解決這個問題,HTML5允許你有一個自由文本輸入和一個下拉列表,它可以作爲一個或一個其他類型的字段來工作,這就是我使它:

fields.py

from django import forms 


class ListTextWidget(forms.TextInput): 
    def __init__(self, data_list, name, *args, **kwargs): 
     super(ListTextWidget, self).__init__(*args, **kwargs) 
     self._name = name 
     self._list = data_list 
     self.attrs.update({'list':'list__%s' % self._name}) 

    def render(self, name, value, attrs=None): 
     text_html = super(ListTextWidget, self).render(name, value, attrs=attrs) 
     data_list = '<datalist id="list__%s">' % self._name 
     for item in self._list: 
      data_list += '<option value="%s">' % item 
     data_list += '</datalist>' 

     return (text_html + data_list) 

forms.py

from myapp.fields import FormForm 

class FormForm(forms.Form): 
    char_field_with_list = forms.CharField(required=True) 

    def __init__(self, *args, **kwargs): 
     _country_list = kwargs.pop('data_list', None) 
     super(FormForm, self).__init__(*args, **kwargs) 

     # the "name" parameter will allow you to use the same widget more than once in the same 
     # form, not setting this parameter differently will cuse all inputs display the 
     # same list. 
     self.fields['char_field_with_list'].widget = ListTextWidget(data_list=_data_list, name='country-list') 

views.py

from myapp.forms import FormForm 

def country_form(request): 
    # instead of hardcoding a list you could make a query of a model, as long as 
    # it has a __str__() method you should be able to display it. 
    country_list = ('Mexico', 'USA', 'China', 'France') 
    form = FormForm(data_list=country_list) 

    return render(request, 'my_app/country-form.html', { 
     'form': form 
    })