在Django中自定义单选按钮

时间:2014-12-31 01:24:46

标签: django

如何在Django中使用自定义单选按钮创建单选按钮表单?

目前我有这个:

from django import forms

TEST_TYPE_CHOICES = ('HDFS', 'HIVE', 'BOTH')

class TestForm(forms.Form):
    # hdfs_test = forms.MultipleChoiceField()
    # hive_test = forms.MultipleChoiceField()
    # hdfs_hive_test = forms.MultipleChoiceField()
    test_type = forms.MultipleChoiceField(required=True, widget=forms.RadioSelect(), choices=TEST_TYPE_CHOICES)
    event_textarea = forms.Textarea(attrs={'rows': '8', 'class': 'form-control', 'placeholder': 'Events...', 'id': 'event_textarea'})

我是Django的新手,在我看来attrs=字段允许添加自定义类。如何添加与MultipleChoiceField类似的内容?

1 个答案:

答案 0 :(得分:0)

你应该这样做,希望这对你有用。

from django import forms

TEST_TYPE_CHOICES = [
('HDFS', 'HDFS'),
('HIVE', 'HIVE'),
('BOTH', 'Both of HDFS and HIVE'),]

class TestForm(forms.Form):
    # hdfs_test = forms.MultipleChoiceField()
    # hive_test = forms.MultipleChoiceField()
    # hdfs_hive_test = forms.MultipleChoiceField()
    test_type = forms.MultipleChoiceField(required=True, widget=forms.RadioSelect(), choices=TEST_TYPE_CHOICES)
    event_textarea = forms.Textarea(attrs={'rows': '8', 'class': 'form-control', 'placeholder': 'Events...', 'id': 'event_textarea'})
    def __init__(self, *args, **kwargs):
        super(metaForm, self).__init__(*args, **kwargs)
        field.widget.attrs['test_type'] = 'your class name here'

或者您也应该这样做:

from django import forms
TEST_TYPE_CHOICES = [
('HDFS', 'HDFS'),
('HIVE', 'HIVE'),
('BOTH', 'Both of HDFS and HIVE'),]

class TestForm(forms.Form):
    # hdfs_test = forms.MultipleChoiceField()
    # hive_test = forms.MultipleChoiceField()
    # hdfs_hive_test = forms.MultipleChoiceField()
    test_type = forms.MultipleChoiceField(required=True, widget=forms.RadioSelect(attrs={'class':'your class name here'}), choices=TEST_TYPE_CHOICES)
    event_textarea = forms.Textarea(attrs={'rows': '8', 'class': 'form-control', 'placeholder': 'Events...', 'id': 'event_textarea'})