django - 如何检查扩展用户模型中的重复项
问题描述
模型 - -
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
Mobile =models.CharField(max_length=15,default="")
def __str__(self):
return self.user.username
形式 - -
class UserProfileForm(forms.ModelForm):
Mobile = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myinput', 'placeholder':'Mobile Number','title':'Please Enter Phone Number Without Country Code, Eg:9999999999 '}),min_length=10, max_length= 15, required =True ,validators = [clean_phone, ])
class Meta:
model = UserProfile
fields=('Mobile',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
self.fields['Mobile'].widget.attrs.update({'class' : 'myinput' ,'placeholder':'Mobile Number','title':'Please Enter Phone Number Without Country Code, Eg:9999999999 '})
看法 - -
# signup form
def signup (request):
if request.method =="POST":
form = signupForm(request.POST or None)
userprofile =UserProfileForm(request.POST or None)
if form.is_valid() and userprofile.is_valid():
try:
First_Name= form.cleaned_data['Name']
email= form.cleaned_data['email']
password= form.cleaned_data['password']
re_password= form.cleaned_data['re_password']
mobile= userprofile.cleaned_data['Mobile']
print(User.userprofile)
if User.objects.filter(username=email).exists() or User.objects.filter(email=email).exists():
print("Email id is already taken")
elif User.userprofile.objects.filter(mobile=mobile).exsist():
print("Mobile Number already taken ")
我想知道用户配置文件中是否已经有手机号码
解决方案
我会将唯一检查放在表单上而不是视图中。
class UserProfileForm(forms.ModelForm):
Mobile = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myinput', 'placeholder':'Mobile Number','title':'Please Enter Phone Number Without Country Code, Eg:9999999999 '}),min_length=10, max_length= 15, required =True ,validators = [clean_phone, ])
class Meta:
model = UserProfile
fields = ('Mobile',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
self.fields['Mobile'].widget.attrs.update({'class' : 'myinput' ,'placeholder':'Mobile Number','title':'Please Enter Phone Number Without Country Code, Eg:9999999999 '})
def clean_mobile(self, data):
value = data['Mobile']
existing_profiles = UserProfile.objects.filter(mobile=value)
if self.instance and self.instance.pk:
existing_profiles = existing_profiles.exclude(pk=self.instance.pk)
if existing_profiles.exists():
raise forms.ValidationError("This phone number has already been taken.")
return value
推荐阅读
- javascript - 如何使用 D3.js 实现过渡持续时间?
- c - C 中 3D 直接卷积实现的优化
- javascript - ReactJS:如何从父组件中清除图像预览
- pytorch - 预训练变压器模型的配置更改
- blockchain - 在私有区块链(对于企业)中,当每个节点都成为潜在的信息泄漏时,如何保护敏感信息的安全?
- java - java进程中是否必须有-XX:PermSize?
- javascript - 如何正确格式化来自背包.tf API 请求的 JSON 数据?
- php - cutenews functions.inc.php php7 错误警告
- python-3.x - 在 Python 类上使用带有 `__next__` 的条件
- node.js - 在 Google App Engine 中托管时如何更新文件?