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的好处是,它也给你使用的环境变量的可能性。