我是Django的新手,python。我想在我的表单中添加单选按钮,但它不起作用。 forms.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']
和我的model.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)
这只显示下拉列表,文本框不显示单选按钮。 请帮帮我。
答案 0 :(得分:2)
在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()
}
答案 1 :(得分:1)
正确使用它的方式。
1)models.py
from django import forms
class ExampleModel(models.Model):
field1 = forms.ChoiceField(widget=forms.RadioSelect)
2)forms.py
class ExampleForm(forms.Form):
field1 = forms.ChoiceField(required=True, widget=forms.RadioSelect(
attrs={'class': 'Radio'}), choices=(('apple','Apple'),('mango','Mango'),))
答案 2 :(得分:0)
你可以试试这个:
gender = forms.ChoiceField(choices=TYPE_SELECT, widget=forms.RadioSelect())