6

フォーム.py

class TypeSelectionForm(forms.Form):
    checkbox_field = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), label="", required=False)

def __init__(self, type_id, *args, **kwargs):
    super(TypeSelectionForm, self).__init__(*args, **kwargs)

    _type_checkbox = self.fields['checkbox_field']       
    MY_CHOICES=((type.id, type.title) for type in type)
    _type_checkbox.choices = MY_CHOICES
    initial_val = []
    type_selection = Types.objects.filter(parent_type_id=type_id,is_active=True)
    for type_selection in type_selection:
        initial_val.append(type_selection.id)
    _type_checkbox.initial = initial_val

ビュー.py

def types(method):
    """"""""""""
    types = TypeSelectionForm(type_id)
    return render(request,'types.html',{'types':types})

テンプレートでは、このようにフィールドをレンダリングしています。

types.html

    {% for field in types.checkbox_field %}                                 
     <div class="deletelist">
     {{field}}<br />
    </div>
   {% endfor %}

このようなhtmlを生成していますが、

<ul>
<li><label for="id_checkbox_field_0"><input checked="checked" type="checkbox" name="checkbox_field" value="597" id="id_checkbox_field_0" /> comp lab</label></li>
<li><label for="id_checkbox_field_1"><input checked="checked" type="checkbox" name="checkbox_field" value="598" id="id_checkbox_field_1" /> phy lab</label></li>
<li><label for="id_checkbox_field_2"><input checked="checked" type="checkbox" name="checkbox_field" value="599" id="id_checkbox_field_2" /> chem lab</label></li>
</ul>

<ul>and<li>タグを次のように置き換えたい<div class="class-name">

助けが必要。

4

4 に答える 4

5

Django テンプレート タグの力を利用してみませんか?

from django import template
from django.utils.safestring import mark_safe
register = template.Library()


@register.filter("as_div")
def as_div(form):
    form_as_div = form.as_ul().replace("<ul", "<div").replace("</ul", "</div")
    form_as_div = form_as_div.replace("<li", "<div").replace("</li", "</div")
    return mark_safe(form_as_div)

それをテンプレートタグに入れて、テンプレートでこれを行うだけです

{% load ad_div %}

{# some Code #}

{{ form|as_div }}

{# some other code #} 

============================

その他のアプローチ (Better Cleaner)

別のアプローチは、djangoフォームモデルを拡張することです

次のように

from django.forms.forms import BaseForm

Class AsDiv(BaseForm):

def as_div(self):
        return self._html_output(
            normal_row = u'<div%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</div>',
            error_row = u'<div>%s</div>',
            row_ender = '</div>',
            help_text_html = u' <span class="helptext">%s</span>',
            errors_on_separate_row = False)

次に、これを行うことができますこれはあなたのテンプレートです

{{ form.as_div }} 
于 2013-09-08T09:20:04.023 に答える
1

ウィジェットは attrs 属性を取り、各入力に属性を追加する必要があります。これを試して:

checkbox_field = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'my-image-class', }), label="", required=False)

アップデート:

したがって、上記の詳細なアプローチは、ラジオ ボタン ウィジェットに対してのみ機能するようです。しかし、あなたが望むものは実際には非常に単純です。チェックボックスを通常どおり出力するだけです。

{% for field in types.checkbox_field %}                                 
 {{field}}
{% endfor %}

これにより、必要に応じてチェックボックスのリストが出力されます。次に、CSS を少し使用して、各リスト項目の背景画像のスタイルを設定します。

form ul li {
background:url("<my-image>") no-repeat center;
width:20px;
height:20px;

}

アップデート

チェックボックスを別の方法でレンダリングする場合は、ウィジェットの仕事であるため、カスタム ウィジェット クラスが必要です。このような何かがあなたを動かします。個人的には、ウィジェットの attrs オプションを使用してクラスを追加しますが、ここでハードコーディングして、あなたが求めていることが可能であることを示しました。

class CheckboxDivSelectMultiple(CheckboxSelectMultiple):
'''renders the checkboxes as divs with a hard coded class'''

def render(self, name, value, attrs=None, choices=()):
    if value is None: value = []
    has_id = attrs and 'id' in attrs
    final_attrs = self.build_attrs(attrs, name=name)
    output = [u'<div>']
    # Normalize to strings
    str_values = set([force_unicode(v) for v in value])
    for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
        # If an ID attribute was given, add a numeric index as a suffix,
        # so that the checkboxes don't all have the same ID attribute.
        if has_id:
            final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
            label_for = u' for="%s"' % final_attrs['id']
        else:
            label_for = ''

        cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
        option_value = force_unicode(option_value)
        rendered_cb = cb.render(name, option_value)
        option_label = conditional_escape(force_unicode(option_label))
        output.append(u'<div class="%s"><label%s>%s %s</label></div>' % ('new-class', label_for, rendered_cb, option_label))
    output.append(u'</div>')
    return mark_safe(u'\n'.join(output))

あなたの形でそれを使用してください:

checkbox_field = forms.MultipleChoiceField(widget=forms.CheckboxDivSelectMultiple(), label="", required=False)
于 2013-09-03T16:50:14.927 に答える