1

我使用django-crispy-forms與Bootstrap,並且我想在爲單個字段呈現的HTML中添加一些額外的HTML 內部向Django香脆表單字段添加額外的HTML標記和屬性

例如,如果我的表單包含,

recipients = forms.CharField(label='To',widget=forms.TextInput(
    attrs={'placeholder': 'Enter phone number, contact or group (add as many as you like)'})) 

然後正常渲染(使用引導模板)是,

<div id="div_id_recipients" class="control-group"> 
    <label for="id_recipients" class="control-label requiredField"> 
     To<span class="asteriskField">*</span> 
    </label> 
    <div class="controls"> 
     <input class="textinput textInput" id="id_recipients" name="recipients" placeholder="Enter phone number, contact or group (add as many as you like)" type="text"> 
    </div> 
</div> 

我想要做的是有一些額外的HTML之前出現最後的收盤價。因此,它會是什麼樣子,

<div id="div_id_recipients" class="control-group"> 
    <label for="id_recipients" class="control-label requiredField"> 
     To<span class="asteriskField">*</span> 
    </label> 
    <div class="controls"> 
     <input class="textinput textInput" id="id_recipients" name="recipients" placeholder="Enter phone number, contact or group (add as many as you like)" type="text"> 
    </div> 

    <div class="controls-aside"> 
     <button type="button" class="btn">Address Book</button> 
     <button type="button" class="btn">Add Contact</button> 
    </div> 

</div> 

我知道我可以替換現有模板與自定義模板這一領域,但我希望能夠重新使用他們的模板而不進行復制/粘貼,因爲這使得它不是很好維護。

那麼實現這個最好的方法是什麼?如果有人可以建議怎麼做,我還想添加額外的類標籤

+0

脆皮形式允許您覆蓋您的表單佈局並添加元素,您是否閱讀文檔?: http://django-crispy-forms.readthedocs.org/en/latest/layouts.html – petkostas 2014-09-19 08:42:42

+0

我已經幾次詳盡無遺地閱讀了文檔。除非我爲它們編寫自定義模板,否則佈局覆蓋不允許我在**需要的控件組內添加內容**。但是,可維護性存在一個問題,因爲我必須將我的模板與標準模板保持一致。我猜目前我的主要選擇是看設計師是否可以改變模板,以便內容可以移到控制組之外。 – richard 2014-09-21 23:42:33

+0

如果你仔細閱讀,你可以通過使用可用的標籤來創建forms.py文件中的表單佈局,特別是'Button('address_book','Address Book')' – petkostas 2014-09-22 07:15:19

回答

2
  1. 爲了完整,但不適合你的情況:即使佈局創建後,如果一個人只需要包裝控制爲附加DivLayout.wrap('recipients', Div)會工作。

  2. 關於在佈局中添加HTML。最後時刻,我需要一個很自定義HTML,所以這樣做:

(格式化)

i = self.helper.layout.fields.index('guest_email') 
self.helper.layout.insert(
    i+1, 
    HTML('<a href="{}">{}</a>'.format(
     reverse_lazy('invite_guests'), 
     _('Invite to a party')) 
)) 

我來到這裏google搜索一個HTMLWrapper類的例子爲脆皮形式,這樣我可以做一個漂亮改爲:

self.helper['guest_email'].wrap(HTMLWrapper(
    'guest_email', 
    before='', 
    after='<a href="{}">{}</a>'.format(href, title)) 

如果我最終創建一個,我會回來併發布它。

0

對我來說,它的工作方式是:

from crispy_forms.layout import Field, HTML 

self.helper["some_field_name"].wrap(Field, HTML("<p>Example</p>")) 

使用HTML的好處是,它也給你使用的環境變量的可能性。