Django Forms无法渲染单选按钮

时间:2016-06-04 18:56:58

标签: python django django-forms

对不起,我对Django很新。我阅读了很多答案,但无法使其发挥作用。我错过了什么

这是我的forms.py

    from django import forms
    from .models import Post
    from django.utils.translation import gettext as _



    class EventsForm(forms.ModelForm):
     class Meta:
        CHOICES=[('select1','select 1'), ('select2','select 2')]
        model = Post
        widgets = {
            'title': forms.TextInput(attrs={'placeholder': _('form-title')}),
            'type_id': forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect),
        }
        fields = ('title', 'type_id', 'post_date', )

我想为 type_id

设置单选按钮

我收到错误

'ChoiceField' object has no attribute 'attrs'

你能解释一下我做错了什么:)

谢谢

2 个答案:

答案 0 :(得分:1)

您会混淆表单字段和小部件。您在widgets dict中指定的内容实际上必须是小部件。

    widgets = {
        'title': forms.TextInput(attrs={'placeholder': _('form-title')}),
        'type_id': forms.RadioSelect(choices=CHOICES),
    }

答案 1 :(得分:0)

这对我有用!

    class EventsForm(forms.ModelForm):
      CHOICES=(('select1','select 1'), ('select2','select 2'))
      type_id = forms.TypedChoiceField(choices=CHOICES, widget=forms.RadioSelect)
      class Meta:
        model = Post
        fields = ('title', 'type_id', 'post_date', )