异常值:“ str”对象没有属性“ get”
异常位置:_get_validation_exclusions中的C:\ Python \ Python38-32 \ Scripts \ myenv \ lib \ site-packages \ django \ forms \ models.py,第346行
models.py
从django.db导入模型
Class HomePageModel(models.Model):
first_name = models.CharField(max_length = 20)
last_name = models.CharField(max_length = 20)
password = models.CharField(max_length = 12)
confirm_password = models.CharField(max_length = 12)
phone_number = models.CharField(max_length = 10)
gender = models.CharField(max_length = 6)
city = models.CharField(max_length = 20)
def __str__(self):
return self.first_name
forms.py
从Django导入表格 从.models导入HomePageModel 从django.core.exceptions导入ValidationError 汇入
Class HomePageForm(forms.ModelForm):
class Meta:
model = HomePageModel
fields = "__all__"
def clean(self):
super(HomePageForm, self).clean()
first_name = self.cleaned_data.get('first_name')
try:
regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
flag_decimal = 0
flag_alpha = 0
if len(first_name) > 20:
raise ValidationError('Fisrt Name can not be more than 20 characters')
if (regex.search(first_name) != None):
raise ValidationError('Fisrt Name can not have a special character')
else:
for char in first_name:
if char.isdecimal():
flag_decimal = 1
if char.isalpha():
flag_alpha = 1
if flag_decimal == 1 or flag_alpha == 0:
raise ValidationError('Fisrt Name can not have a number')
return first_name
except ValidationError as e:
print(e)
.... #rest验证
views.py
从django.shortcuts导入从django.http导入HttpResponse 从.forms导入HomePageForm
def home_page(请求):
if request.method == 'POST':
form = HomePageForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse('Successful')
else:
return render(request, "home.html", {'form':form})
else:
form = HomePageForm()
return render(request, "home.html", {'form':form})
模板
<body>
<h2>Home Page</h2>
<form action = "" method = "POST" enctype="multipart/form-data">
{%csrf_token %}
{{ form.as_p }}
<input type="submit" value='Submit'>
</form>
</body>
请帮助我解决此错误。 谢谢!
答案 0 :(得分:0)
尝试将表单中函数的名称从clean更改为clean_first_name