gpt4 book ai didi

python - Django 中的单选按钮

转载 作者:太空宇宙 更新时间:2023-11-03 19:56:18 25 4
gpt4 key购买 nike

尝试寻找解决方案,但我有一个不同的问题,但找不到与之相关的任何内容我创建了一个 django 表单,其中包含 models.py 中的字段

表单.py

from .models import ProValue
from django import forms


class SchoolInput(forms.ModelForm):
school_name = forms.CharField(
max_length=255, required=True, widget=forms.TextInput(
attrs={
'class': 'input'
}
))
level_of_grades = forms.IntegerField(min_value=1, required=True)
num_of_days = forms.IntegerField(min_value=1, max_value=7, required=True)
division_check = forms.ChoiceField(
label='Do you have multiple divisions for your grades?', widget=forms.RadioSelect)

class Meta:
model = ProValue
answer = (
('no', 'no'),
('yes', 'yes')
)
fields = [
'school_name',
'level_of_grades',
'num_of_days',
'division_check',
]

这样我就看不到页面上的单选按钮了我尝试过这样做

    division_check = forms.ChoiceField(
label='Do you have multiple divisions for your grades?', widget=forms.RadioSelect())

    division_check = forms.ChoiceField(
label='Do you have multiple divisions for your grades?', widget=forms.RadioSelect(choice=answer))

这告诉我答案未定义

这是我的 models.py

from django.db import models
from django import forms


class ProValue(models.Model):
school_name = models.CharField(max_length=50)
level_of_grades = models.IntegerField()
num_of_days = models.IntegerField()
answer = (
('Yes', 'Yes'),
('No', 'No'),
)
division_check = models.CharField(
max_length=5, choices=answer)

另外,我需要在 Meta 类中再次定义答案吗?我一开始没有这样做,我尝试解决上述问题但仍然无法解决。

最佳答案

您在 Meta 类中定义了 answer,但它不在您定义小部件时的范围内。

您可以引用模型中的选项,例如:

from .models import ProValue
from django import forms


class SchoolInput(forms.ModelForm):
school_name = forms.CharField(
max_length=255, required=True, widget=forms.TextInput(
attrs={
'class': 'input'
}
))
level_of_grades = forms.IntegerField(min_value=1, required=True)
num_of_days = forms.IntegerField(min_value=1, max_value=7, required=True)
division_check = forms.ChoiceField(
label='Do you have multiple divisions for your grades?',
<b>choices=ProValue.answer</b>,
widget=forms.RadioSelect
)

class Meta:
model = ProValue
fields = [
'school_name',
'level_of_grades',
'num_of_days',
'division_check',
]

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com