我正在尝试在Django表单选择字段中设置一些默认值,在该字段中我向用户询问他的生日和他所居住的城市,我已经尝试过在表单中传递参数“ initial”并添加属性值,但是不起作用。
这是我的代码...
forms.py
class RegisterForm2(forms.Form):
gender = forms.ChoiceField(choices = gender_choices,required=True)
birthdate = forms.DateField(widget
=forms.SelectDateWidget(years=range(1900, 2020)))
marital_status = forms.ChoiceField(choices = marital_status,
required=True)
districts = forms.ChoiceField(choices = districts, required=True)
city = forms.CharField(widget = forms.TextInput(attrs=
{'id':'id_cidade', 'placeholder':'Nome da cidade onde vives'}))
job = forms.CharField(widget = forms.TextInput(attrs=
{'id':'id_profissao', 'placeholder':'A tua Profissão'}))
class meta:
model = UserRegister
fields = ['gender',
'birthdate',
'marital_status',
'districts',
'city',
'job']
choices.py
gender_choices = (('F', 'Feminino'), ('M', 'Masculino'))
marital_status = (('S','Solteiro'), ('D', 'Divorciado'), ('V',
'Viuvo'), ('C', 'Casado'))
districts = (('Aveiro','Aveiro'), ('Beja','Beja'), ('Braga','Braga'),
('Bragança','Bragança'), ('Castelo Branco','Castelo Branco'),
('Coimbra','Coimbra'), ('Évora', 'Évora'),('Faro','Faro'),
('Guarda','Guarda'),('Ilha da Madeira','Ilha da Madeira'),('Ilha dos
Açores','Ilha dos Açores'),('Leiria','Leiria'),('Lisboa','Lisboa'),
('Portalegre','Portalegre'),('Porto','Porto'),
('Santarém','Santarém'),('Setúbal','Setúbal'),('Viana do
Castelo','Viana do Castelo'),
('Vila Real','Vila Real'),('Viseu','Viseu'))
答案 0 :(得分:0)
默认情况下,ChoiceField的初始值是它的第一个元组,如果您和任何初始值都将该值作为快速元组传递。
gender_choices = (('initial', "choose"),('F', 'Feminino'), ('M', 'Masculino'))
答案 1 :(得分:0)
你可以试试吗
MALE = 'M'
FEMALE = 'F'
gender_choices = (
(MALE, 'Feminino'),
(FEMALE, 'Masculino'))
对于应该起作用的所有选择都这样做。