不显示Django表单字段

时间:2013-10-09 22:45:45

标签: django django-forms

我正在尝试在视图中输出表单字段。 但是我得到了: django.forms.widgets.Select对象位于0x7f631c2cef10 而不是html select元素

我的代码:

forms.py

class SearchForm(forms.Form):
  def __init__(self, *args, **kwargs):
      from house.models import COUNTRY_LIST, HOUSE_TYPES
      from profile.models import Region
      self.countries = forms.Select(choices=COUNTRY_LIST, attrs={'title': 'Страна','class': 'search-r-from-select style-select'})
      self.type = forms.Select(choices=HOUSE_TYPES, attrs={'class': 'search-r-from-select style-select'})
      super(SearchForm, self).__init__(*args, **kwargs)

views.py

def search_view(request):
  from house.models import House
  from house.forms import SearchForm
  if request.GET.get('initSearch', False):
     found_houses = House.get_search_result(request.GET)
     search_form = SearchForm(request.GET)
  else:
     search_form = SearchForm()

  return render_template(request, 'house/search.html', {
     'search_form': search_form
  })

内部/搜索/ HTML

  {{ search_form.countries }}

1 个答案:

答案 0 :(得分:1)

将代码更改为以下内容:

 from house.models import COUNTRY_LIST, HOUSE_TYPES
 from profile.models import Region

 class SearchForm(forms.Form):
     def __init__(self, *args, **kwargs):
         super(SearchForm, self).__init__(*args, **kwargs)
         self.fields['countries'] = forms.ChoiceField(choices=COUNTRY_LIST, widget=forms.Select(attrs={'title': 'Страна','class': 'search-r-from-select style-select'}))
         self.fields['type'] = forms.ChoiceField(choices=HOUSE_TYPES, widget=forms.Select(attrs={'class': 'search-r-from-select style-select'}))