我的表单验证有问题,我创建了验证电子邮件是否存在的方法,因此,如果它确实存在则数据无法保存在数据库中,但在我个人的情况下它仍然保存它
这是我的代码:
models.py:
from django.db import models
from promSpace.models import Space
class StudentRegistration(models.Model):
email = models.EmailField(max_length=50)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
password = models.CharField(max_length=20, default="", null=False)
prom_code = models.CharField(max_length=8, default="", null=False)
gender = (
("M","Male"),
("F","Female"),
)
gender = models.CharField(max_length=1, choices=gender, default="M", null=False)
prom_name = models.CharField(max_length=20, default="N/A")
forms.py:
from django import forms
from django.contrib.auth.models import User
#from models import StudentRegistration
from django.forms import ModelForm
from promSpace.models import Space
from StudentUsers.models import StudentRegistration
from django.contrib.auth.forms import UserCreationForm
class MyRegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(widget=forms.PasswordInput)
prom_code = forms.CharField(max_length = 8)
email = forms.EmailField(max_length=50)
def email_al_exist(self):
email = self.cleaned_data['email']
if StudentRegistration.objects.filter(email = email).exists():
raise ValidationError("Email already exists")
return email
def clean_password2(self):
password = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
if password and password2:
if password != password2:
raise forms.ValidationError(("The two password fields didn't match."))
return password2
def prom_code_exist(self):
prom_code_value = self.cleaned_data['prom_code']
prom_code_ver = Space.objects.get(prom_code = prom_code_value)
if Space.objects.filter(prom_code = prom_code_value).exists():
return prom_code_value
else:
raise forms.ValidationError(("Error, Code doesn't exist."))
class Meta:
model = StudentRegistration
fields = ('email', 'first_name', 'last_name','gender','prom_code','password')
观察:我在这里创建的用户被保存在他们自己的表(StudentRegistration)中,他们与auth_user(默认的)没有关系
答案 0 :(得分:1)
您的email_al_exist
方法永远不会被调用。当然不在你在这里发布的代码中。您可能应该将其重命名为clean_email。
def clean_email(self):
email = self.cleaned_data['email']
if StudentRegistration.objects.filter(email = email).exists():
raise ValidationError("Email already exists")
return email