我是 Django 和 Python 的新手。我想在我的表单中添加一个单选按钮,但它不起作用。
表单.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.forms.widgets import RadioSelect
from choicebtn.models import myChoice
class myChoiceForm(UserCreationForm):
name=forms.CharField(max_length=55)
TYPE_SELECT = (('0', 'Female'),('1', 'male'),)
gender=forms.ChoiceField(widgets.RadioSelect(choices=TYPE_SELECT))
class Meta:
model = myChoice
fields = ['name','gender']
模型.py:
from django.db import models
from django.forms.widgets import RadioSelect
from django.urls import reverse
class myChoice(models.Model):
name=models.CharField(max_length=55)
TYPE_SELECT = (('0', 'Female'),('1', 'male'),)
gender=models.CharField(max_length=11,choices=TYPE_SELECT)
这只显示下拉列表 和文本框。它不显示单选按钮。 请帮助我。
最佳答案
在 models.py 中:
class myChoice(models.Model):
name = models.CharField(max_length=55)
TYPE_SELECT = (
('0', 'Female'),
('1', 'male'),
)
gender = models.CharField(max_length=11,choices=TYPE_SELECT)
在 forms.py 中:
class myChoiceForm(ModelForm):
class Meta:
model = myChoice
fields = ['__all__']
widgets = {
'gender': forms.RadioSelect()
}
关于python - 如何在 Django 中创建单选按钮,哪些字段在表单和模型中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45838053/