1

我正在使用django-crispy-forms和 bootstrap 来呈现我的 django 表单。

我想使用像这里这样的文件上传字段,但我不确定如何让我的 html 像这样输出:

<div class="fileupload fileupload-new" data-provides="fileupload">
  <div class="fileupload-new thumbnail" style="width: 50px; height: 50px;"><img src="http://www.placehold.it/50x50/EFEFEF/AAAAAA" /></div>
  <div class="fileupload-preview fileupload-exists thumbnail" style="width: 50px; height: 50px;"></div>
  <span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" /></span>
  <a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
</div>

使用 aModelForm给我这样的输出:

<div id="div_id_my_id" class="control-group">
  <label class="control-label " for="id_my_id"> My Model Field</label>
  <div class="controls">
</div>

对于这样的表格:

class MyForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.layout = Layout(
            Div(
                Div('stuff', 'things' css_class='span6'),
                Div('main_image', 'my_id', css_class='span6' ),
            css_class='row-fluid'),
        )

    class Meta:
        model=MyForm

所以我需要添加一个 div、一个 span 并更改它们的一些属性。你遇到过这个问题吗?谢谢你的想法!

4

1 回答 1

4

你可以这样做:

from crispy_forms.layout import Field

class FileField(Field):
    template = 'bootstrap/layout/file_field.html'

file_field.html

{% load crispy_forms_field %}

<div id="div_{{ field.auto_id }}" class="control-group{% if form_show_errors%}{% if field.errors %} error{% endif %}{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}">
    {% if field.label %}
        <label for="{{ field.id_for_label }}" class="control-label {% if field.field.required %}requiredField{% endif %}">
            {{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
        </label>
    {% endif %}

    <div class="controls">
        <div class="fileupload fileupload-new" data-provides="fileupload">
          <div class="fileupload-new thumbnail" style="width: 50px; height: 50px;"><img src="http://www.placehold.it/50x50/EFEFEF/AAAAAA" /></div>
          <div class="fileupload-preview fileupload-exists thumbnail" style="width: 50px; height: 50px;"></div>
          <span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" name="{{ field.html_name }}" id="id_{{ field.html_name }}" value="{{ field.value }}" /></span>
          <a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
        </div>
        {% include 'bootstrap/layout/help_text_and_errors.html' %}
    </div>
</div>

然后在你的 FormHelper 中使用它作为FileField('main_image').

于 2013-01-30T09:19:53.507 回答