场景: 我实例化一个ModelForm并将其传递给显示表单的模板。提交POST后,代码将尝试通过任何给定的输入来搜索数据库。我不需要像模型中那样输入所有输入。我只需要输入一个(或多个,如果用户希望进行AND搜索)即可。
问题:如何使任何ModelForm字段为可选,而在Model中,该字段不是可选的。该字段在模型中不是可选的,因为我还有一个基于同一模型的ModelForm,要求用户输入其所有详细信息。
我的模特:
class customer(models.Model):
# Need autoincrement, unique and primary
cstid = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=35)
age=models.IntegerField()
gender_choices = (('male', 'Male'),
('female', 'Female'))
gender = models.CharField(
choices=gender_choices, max_length=10, default='male')
maritalstatus_choices = ( ('married', 'Married'),
('unmarried', 'Unmarried'))
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='')
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-'),
('unspecified', '-')
)
bloodgroup = models.CharField(choices=bloodgroup_choices, max_length=3, default='-', blank=True)
class Meta:
unique_together = ["name", "mobile", "age"]
def __str__(self):
return self.name
我的表单:
class CheckinPatientMetaForm(ModelForm):
class Meta:
model = customer
exclude = [
'gender',
'maritalstatus',
'occupation',
'bloodgroup'
]
views.py:
def checkin_patient(request):
results = ''
if request.method == 'POST':
form = CheckinPatientMetaForm(request.POST)
print("POST data",request.POST)
else:
form = CheckinPatientMetaForm()
return render(request, 'clinic/checkin.html', {'rnd_num': randomnumber(), 'form': form, 'SearchResults': results})
答案 0 :(得分:1)
如评论中提到的@bdbd一样,您可以通过 handleRemoveFavourite = (history) => {...}
进行指定。
例如,如果您希望required=False
字段为可选字段,则将其显式添加为
age