python - Django Forms 无法呈现单选按钮

标签 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'

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

谢谢

最佳答案

这对我有用!

    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', )

关于python - Django Forms 无法呈现单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37633882/

相关文章:

python - Django 从列表中自动填充表单

python - Django,重定向的网址不正确

python - 按日期更改 URL 的 Web 抓取

python - 将比率字段插入 Pandas 系列

python - 在 Django 中查询 ManyToMany 给我重复的结果

python - 返回两个模型的多对多字段中的 django 用户

即使使用非捕获组,Python re.sub() 也会替换完整匹配项

django - TemplateDoesNotExist 错误,但模板确实存在

python - Django过滤器 'first'查找多对多关系

python - 从 Django 中的几种形式收集信息