我无法覆盖Django ModelForm,
forms.py
class CustomerForm(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Customer Name '}))
address = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Customer Address'}))
phone_number = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Customer Phone Number '}))
email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Customer Email'}))
contact_person = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Contact person'}))
amc_date = forms.DateField(widget=forms.TextInput(attrs={'placeholder': 'ex: Jan 20, 1996'}))
amc_product = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Products listed in AMC'}))
warranty_date = forms.DateField(required=False, widget=forms.TextInput(attrs={'placeholder': 'ex: Jan 20, 1996'}))
warranty_product_list = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Products listed in warranty'}))
support = forms.ChoiceField(choices=support_choice, required=True,)
class Meta:
model = Customer
fields = ['name','address','phone_number','email','contact_person','support','amc_date','amc_product','warranty_date',
'warranty_product_list']
def clean_amc_date(self):
amc_date = self.cleaned_data.get("amc_date")
if amc_date == "":
amc_date = 0
return amc_date
def clean_amc_product(self):
amc_product = self.cleaned_data.get("amc_date")
if amc_product == "":
amc_product = 0
return amc_product
在提交表单时,错误显示为“此字段是必需的”。
答案 0 :(得分:0)
请参阅how validators are run in forms上的文档。基本上,内置字段验证在clean_*
方法之前运行;因此,如果您想在此时允许空白值,则需要使用required=False
:
amc_date = forms.DateField(required=False, widget=forms.TextInput(attrs={'placeholder': 'ex: Jan 20, 1996'}))
amc_product = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Products listed in AMC'}))