我有以下内容:
型号:
class customer(models.Model):
cstid = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=35)
ageyrs=models.IntegerField(blank=True)
agemnths=models.IntegerField(blank=True)
dob = models.DateField(null=True, blank=True)
gender_choices = (('male', 'Male'),
('female', 'Female'),
('other', 'Something else'),
('decline', 'Decline to answer'))
gender = models.CharField(
choices=gender_choices, max_length=10, default='male')
maritalstatus_choices = (('unmarried', 'Unmarried'),
('married', 'Married'))
maritalstatus = models.CharField(
choices=maritalstatus_choices, max_length=10, default='Unmarried')
mobile = models.CharField(max_length=15, default='')
alternate = models.CharField(max_length=15, default='', blank=True)
email = models.CharField(max_length=50, default='', blank=True)
address = models.CharField(max_length=80, default='', blank=True)
city = models.CharField(max_length=25, default='', blank=True)
occupation = models.CharField(max_length=25, default='', blank=True)
bloodgroup_choices = (('apos', 'A+'),
('aneg', 'A-'),
('bpos', 'B+'),
('bneg', 'B-'),
('opos', 'O+'),
('oneg', 'O-'),
('abpos', 'AB+'),
('abneg', 'AB-')
)
bloodgroup = models.CharField(choices=bloodgroup_choices, max_length=5, default='-', blank=True)
class Meta:
unique_together = ["name", "mobile", "linkedclinic"]
我的ModelForm:
class RegisterPatientMetaForm(ModelForm):
class Meta:
dob = forms.DateField(input_formats=['%d-%m-%Y'])
model = customer
fields = [
'name',
'ageyrs',
'agemnths',
'dob',
'gender',
'maritalstatus',
'mobile',
'alternate',
'email',
'address',
'city',
'occupation',
'bloodgroup'
]
在我的模板中,我有:
<div class="col-md-8">
<label for="gender">Date of Birth</label>
{{ form.dob }}
</div>
问题是日期显示为%Y-%m-%d,而我希望日期显示为%d-%m-%Y。我怎么做呢?我该如何解决?
答案 0 :(得分:1)
当您覆盖表单的字段时,需要将其作为类的属性而不是放在元类中。像这样:
class RegisterPatientMetaForm(ModelForm):
dob = forms.DateField(input_formats=['%d-%m-%Y']) # <-- removed it from meta and put it here
class Meta:
model = customer
fields = [
'name',
'ageyrs',
'agemnths',
'dob',
'gender',
'maritalstatus',
'mobile',
'alternate',
'email',
'address',
'city',
'occupation',
'bloodgroup'
]
答案 1 :(得分:1)
@ruddra的回答仅部分正确。 我的问题有两个不同方面。一方面,我需要以选定的日期格式显示现有的数据库行。为此,我需要自定义form.DateInput小部件,以便正确显示现有值。第二,我也需要接受所选格式的输入。
因此,解决方案如代码所示:
D
此处,class RegisterPatientMetaForm(ModelForm):
dob = forms.DateField(
input_formats=['%d-%m-%y'],
widget=forms.DateInput(format='%d-%m-%y')
)
class Meta:
model = customer
fields = [
'name',
'ageyrs',
'agemnths',
'dob',
'gender',
'maritalstatus',
'mobile',
'alternate',
'email',
'address',
'city',
'occupation',
'bloodgroup'
]
error_messages = {
}
unique_together = ["name", "mobile", "linkedclinic"]
列表决定接受哪些日期格式作为输入(请参见Docs)。 input_formats=['%d-%m-%y']
使初始字段正确显示时(请参见Docs)