python - 我的 EmployeeForm 类中的“Employee_Name”的自定义验证不起作用
问题描述
我制作了一个表格来创建员工详细信息。在 forms.py 中,我创建了 EmployeeForm 类,还添加了一个自定义验证来验证“Employee_Name”,但自定义验证“EmployeeNameValidate”不起作用。
表格.py
class EmployeeForm (forms.ModelForm):
Employee_Name = forms.CharField(widget=forms.TextInput(attrs{
"placeholder" : "Enter the Employee Name "
}
))
Employee_ID = forms.CharField(initial = '17CS')
Address = forms.CharField(
required = False ,
widget = forms.Textarea
(
attrs={
"placeholder": "Enter your Address here ",
"class" : "new-class-name two",
"id" :"my-id-for-textarea",
"rows":10,
"cols":100
}
)
)
Salary = forms.DecimalField(initial = 60000.24)
class Meta:
model = Employee
fields = [
'Employee_Name',
'Employee_ID',
'Address',
'Salary'
]
#print("yaaah !!")
def EmployeeNameValidate(self, *args , **kwargs):
print("yaaah 22222 !!")
Employee_Name = self.cleaned_data.get("Employee_Name")
print(Employee_Name)
if "abc" not in Employee_Name:
raise forms.ValidationError ("This is not a valid Employee Name
")
return Employee_Name
#print("yaaah 3333333333!!")
视图.py
def emp_create_view(request):
form = EmployeeForm(request.POST or None )
if form.is_valid():
form.save()
form = EmployeeForm()
context={
'form': form
}
return render(request,"employee/emp_create.html",context)
emp_create.html
{% extends "base.html" %}
{% block content %}
<h1>
Enter the details of the Employee :
</h1>
<form method = 'POST'> {% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Save' />
</form>
{% endblock %}
解决方案
您的验证方法必须名称为 clean_Employee_Name,因为您的字段名称为 Employee_Name
尝试这个
class EmployeeForm (forms.ModelForm):
Employee_Name = forms.CharField(widget=forms.TextInput(attrs{
"placeholder" : "Enter the Employee Name "
}
))
Employee_ID = forms.CharField(initial = '17CS')
Address = forms.CharField(
required = False ,
widget = forms.Textarea
(
attrs={
"placeholder": "Enter your Address here ",
"class" : "new-class-name two",
"id" :"my-id-for-textarea",
"rows":10,
"cols":100
}
)
)
Salary = forms.DecimalField(initial = 60000.24)
class Meta:
model = Employee
fields = [
'Employee_Name',
'Employee_ID',
'Address',
'Salary'
]
#print("yaaah !!")
def clean_Employee_Name(self, *args , **kwargs):
print("yaaah 22222 !!")
Employee_Name = self.cleaned_data.get("Employee_Name")
print(Employee_Name)
if "abc" not in Employee_Name:
raise forms.ValidationError ("This is not a valid Employee Name
")
return Employee_Name
#print("yaaah 3333333333!!")
希望有帮助
推荐阅读
- java - SoapUI 如何获取每个 TestStep 的请求和响应大小
- mysql - spring boot jpa:ddl-auto=create 不创建模式
- perl - Perl 失败的语言环境。你是怎么设置的?
- keycloak - 在 Keycloak 扩展中实现 AbstractOAuth2IdentityProvider 时出现 NoClassDefFoundError
- python - 为什么我不能让我的“def”函数正确输出文本?
- android - 如何使用 Spinner 从显示文本中获取不同的返回值?
- java - 无法序列化包含 orientdb 记录 ID 的地图
- javascript - 使用键值中的“:”访问 JSON 值
- java - 如何 JavaDoc 动作监听器
- jms - 挂起状态下的 Tibco JMS 队列发件人活动