7

表格.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)

模板.py

更新:

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

上面的表单在无序列表中呈现单选按钮,但我希​​望没有无序列表。我该怎么做?

4

2 回答 2

17

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

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()})
于 2013-05-13T13:28:45.593 回答
5

您可以遍历RadioSelect模板中的

{% for choice in form.date_format %}
  {{ choice.choice_label }}
  <div class="select">{{ choice.tag }}</div> {# Or any other type you want. #}
{% endfor %}
于 2013-05-13T13:23:49.130 回答