如何在django中渲染没有ul的单选按钮

时间:2013-05-13 12:56:18

标签: django django-forms django-templates

forms.py

Date_Format = (
    ('0', ' dd / mm / yyyy'),
    ('1', 'mm / dd / yyyy'),
)    
Time_Format = (
    ('0', ' 12 hour AM / PM '),
    ('1', ' 24 hour '),
)
class SettingsForm(forms.ModelForm):
    date_format = forms.ChoiceField(widget=forms.RadioSelect(), choices=Date_Format)
    time_format = forms.ChoiceField(widget=forms.RadioSelect(), choices=Time_Format)

template.py

更新

                    {% for radio in SettingsForm.date_format %}
                    {{ radio.choice_label }}
                    <div class="select">{{ radio.tag }}</div>
                    {% endfor %}

上面的表格是将单选按钮呈现在无序列表中,但我希望在无序列表中使用。我怎么能这样做?

2 个答案:

答案 0 :(得分:16)

您可以创建自定义渲染器:

from django import forms
from django.forms.widgets import RadioFieldRenderer
from django.shortcuts import render
from django.utils.html import format_html_join
from django.utils.encoding import force_text


class RadioFieldWithoutULRenderer(RadioFieldRenderer):

    def render(self):
        return format_html_join(
            '\n',
            '<li>{0}</li>',
            [(force_text(w), ) for w in self],
        )


CHOICES = (
    ('0', ' 12 hour AM / PM '),
    ('1', ' 24 hour '),
)


class MyForm(forms.Form):
    somefield = forms.ChoiceField(
        widget=forms.RadioSelect(renderer=RadioFieldWithoutULRenderer),
        choices=CHOICES)


def myview(request):
    return render(request, 'form.html', {'form': MyForm()})

答案 1 :(得分:4)

您可以遍历模板中的RadioSelect

{% for choice in form.date_format %}
  {{ choice.choice_label }}
  <div class="select">{{ choice.tag }}</div> {# Or any other type you want. #}
{% endfor %}