编程语言
首页 > 编程语言> > Django / Python,在Modelform中将单选按钮用于布尔字段?

Django / Python,在Modelform中将单选按钮用于布尔字段?

作者:互联网

这个问题已经在这里有了答案:            >            Django BooleanField as radio buttons?                                    10个
我正在尝试在模型窗体中使用单选按钮,但是当我以这种方式进行覆盖时,它只是不输出任何内容(它只是在表单中打印标签,而不是单选按钮,如果不进行覆盖,它将执行标准复选框)

我的模型字段定义为:

Class Mymodelname (models.Model):
    fieldname = models.BooleanField(max_length=1, verbose_name='ECG')

我的模型形式是这样定义的:

from django.forms import ModelForm
from django import forms
from web1.myappname.models import Mymodelname

class createdbentry(forms.ModelForm):

    choices = ( (1,'Yes'),
                (0,'No'),
              )

    fieldname = forms.ChoiceField(widget=forms.RadioSelect
            (choices=choices))

我将不胜感激任何关于我做错事的建议..谢谢

class Meta:
    model = Mymodelname

解决方法:

这样行吗?

class createdbentry(forms.ModelForm):

    choices = ( (1,'Yes'),
                (0,'No'),
              )

    class Meta:
        model = Mymodelname

    def __init__(self, *args, **kwargs):
        super(createdbentry, self).__init__(*args, **kwargs)

        BinaryFieldsList = ['FirstFieldName', 'SecondFieldName', 'ThirdFieldName']
        for field in BinaryFieldsList:
            self.fields[field].widget = forms.RadioSelect(choices=choices)

标签:forms,django-forms,python,django,radio-button
来源: https://codeday.me/bug/20191209/2096762.html