2012-11-09 44 views
1

我創建一個自定義窗口小部件的日期時間字段:如何從窗口小部件定義中訪問Django窗口小部件的ID?

class MySplitDateTimeWidget(forms.SplitDateTimeWidget): 
    def format_output(self, rendered_widgets): 
     mytimeid = self.widgets[1].attrs['id'] #####NEED HELP HERE 
     temp = "javascript:$('%s').val(new Date().getHours());" % mytimeid 
     temp1 = '<a href="%s">Now</a>' % temp 
     return mark_safe(u'%s %s<br />%s %s %s' % \ 
      (_('Date:'), rendered_widgets[0], _('Time:'), rendered_widgets[1], 
      temp1 
     )) 

我需要的小工具的「id」屬性,但是self.widgets不包括ATTRS的「id」屬性。它包括所有其他屬性。我不確定這個屬性來自哪裏?

回答

0

除非你重寫吧,ID應該是:

id_[name]

所以嘗試:

mytimeid = 'id_'+self.widgets[1].attrs['name'] 
+0

的ATTRS對象不包含「名稱」要麼。這些值似乎在某個時間點被傳遞給了小部件,但它對於我來說不知道從哪裏或者從哪裏。 – rsp

+0

嗯......如果您試圖將MultiWidget轉換爲子類(SplitDateTimeWidget基於哪個),您會得到相同的結果嗎?你必須定義一個__init__ ...像這樣:像這樣... class MySplitDateTimeWidget(forms.MultiWidget): def __init __(self,attrs = None): widgets =(forms.widgets.DateInput(attrs = attrs),forms.widgets.TimeInput(attrs = attrs)) super(MySplitDateTimeWidget,self).__ init __(widgets,attrs) – jlmcdonald

+0

如果我嘗試這個子類方法,我得到這個錯誤:Caught NotImplementedError while rendering:Subclasses must implement this方法。我不確定它在那裏指的是什麼?我花了更多時間瀏覽django和管理源,我不確定是否有方法從format_output方法獲取id。 django管理員在加載頁面後使用一些客戶端JavaScript將這種類型的功能添加到小部件。 – rsp

1

我只是用完全相同的拼殺;希望這對其他人有用。 「標識」 attr爲通過設置:

  1. 形式要求本身呈現通過其領域
  2. 對於每個字段
  3. 表格迭代,調用的形式其定製__getitem__()它包裝領域作爲一個BoundField
  4. 的綁定列,在as_widget()方法,是實際設置「id」屬性(另見auto_id()法)
  5. 的MultiWidget然後執行它的render()方法,這使得它的每個子控件,然後加入他們與format_output()

因此,要回答你的問題,你想在render()方法的ID,而不是format_output()方法:

class MySplitDateTimeWidget(forms.SplitDateTimeWidget): 
    def render(self, name, value, attrs=None): 
     widgets_html = super(MySplitDateTimeWidget, self).render(name, value, attrs) 

     # attrs['id'] is the ID of the entire widget, append the prefix to chose the sub-widget 
     mytimeid = attrs['id'] + '_0' 
     temp = "javascript:$('%s').val(new Date().getHours());" % mytimeid 
     temp1 = '<a href="%s">Now</a>' % temp 

     return mark_safe(widgets_html + ' ' + temp1) 

    def format_output(self, rendered_widgets): 
     return mark_safe(u'%s %s<br />%s %s' % (_('Date:'), rendered_widgets[0], _('Time:'), rendered_widgets[1])) 
相關問題