2012-09-06 45 views
2
class CreateCourseForm(ModelForm): 
     category = forms.ModelChoiceField(
      queryset=Category.objects.all(), 
      empty_label="", 
      #widget=CustomCourseWidget() 
     ) 

    class Meta: 
     model = Course 
     fields = ('title', 'description', 'category') 

    def __init__(self, *args, **kwargs): 
     super(CreateCourseForm, self).__init__(*args, **kwargs) 
     self.fields['category'].widget.attrs['class'] = 'chzn-select' 
     self.fields['category'].widget.attrs['data-placeholder'] = u'Please select one' 

通過上面的代碼,我得到了列出所有類別對象的選擇框。我正在嘗試添加一個Django Forms和ModelChoiceField:將HTML optgroup元素添加到QuerySet中的特定對象?

<optgroup>VALUE</optgroup> 

將HTML元素添加到特定的類別對象(Category.parent == null)。

有誰知道該怎麼做?非常感謝!我已經嘗試將QuerySet轉換爲選擇集(例如http://dealingit.wordpress.com/2009/10/26/django-tip-showing-optgroup-in-a-modelform/),該工具可以很好地呈現HTML,直到我嘗試將結果保存到發生不匹配的數據庫(ValueError)時爲止。

+0

您在引用,或其變體的方法是做到這一點的方法。恢復到您所擁有的內容,然後發佈堆棧跟蹤以獲取您遇到的錯誤。 –

+0

我已經使用自定義小部件創建了一個解決方案。我會盡快回復我自己的問題。 –

回答

1

這是我目前的解決方案。這可能是一個骯髒的修復程序,但它工作正常:-)

class CustomCourseWidget(forms.Select): 
    #http://djangosnippets.org/snippets/200/ 
    def render(self, name, value, attrs=None, choices=()): 
     from django.utils.html import escape 
     from django.utils.encoding import smart_unicode 
     from django.forms.util import flatatt 

     if value is None: 
      value = '' 
     final_attrs = self.build_attrs(attrs, name=name) 
     output = [u'<select%s>' % flatatt(final_attrs)] 
     output.append(u'<option value=""></option>') # Empty line for default text 
     str_value = smart_unicode(value) 
     optgroup_open = False 
     for group in self.choices: 
      option_value = smart_unicode(group[0]) 
      option_label = smart_unicode(group[1]) 
      if not ">" in option_label and optgroup_open == True: 
       output.append(u'</optgroup>') 
       optgroup_open = False 
      if not ">" in option_label and optgroup_open == False: 
       output.append(u'<optgroup label="%s">' % escape(option_label)) 
       optgroup_open = True 
      if " > " in option_label: 
       #optgroup_open = True 
       selected_html = (option_value == str_value) and u' selected="selected"' or '' 
       output.append(u'<option value="%s"%s>%s</option>' % (escape(option_value), selected_html, escape(option_label.split(" > ")[1]))) 

     output.append(u'</select>') 
     return mark_safe(u'\n'.join(output))