在我的 django 帳戶應用程式中,我想檢查資料庫中是否存在輸入的電子郵件(基本 django db.sqlite3)。
表格.py:
from django import forms
from django.contrib.auth.models import User
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(label='Has?o', widget=forms.PasswordInput)
password2 = forms.CharField(label='Powtórz has?o', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username', 'first_name', 'email')
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('Has?a nie s? identyczne.')
return cd['password2']
視圖.py:
def register(request):
if request.method == "POST":
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
# Creating new user object, without saving in database
new_user = user_form.save(commit=False)
# Setting new password
new_user.set_password(
user_form.cleaned_data['password'])
# Saving user object
new_user.save()
return render(request,
'account/register_done.html',
{'new_user': new_user})
else:
user_form = UserRegistrationForm()
return render(request,
'account/register.html',
{'user_form': user_form})
現在,當我為另一個用戶輸入相同的電子郵件時,表單會創建該用戶。
我認為有可能以這種方式做到這一點嗎?1)。將電子郵件設為變數,如密碼和密碼 2 2)。從元 3 中洗掉電子郵件)。創建方法 clean_email() 并檢查電子郵件是否存在于資料庫中,如果不引發錯誤
我不知道如何在 db 中獲取電子郵件
感謝所有幫助!
uj5u.com熱心網友回復:
下面is_valid():在你views.py做這個
if user_form.is_valid():
new_user = user_form.save(commit=False)
email=user_form.cleaned_data['email']
if not User.objects.filter(email=email).exists():
//the rest of your code
else:
//some error message
這可確保僅在新用戶不存在時才創建新用戶。
如果您正在開發一個需要用戶名、電子郵件和密碼長度為 x(在本例中為 8)的應用程式,請執行此操作。
if not User.objects.filter(username=username).exists():
if not User.objects.filter(email=email).exists():
if len(password) < 8:
// some error message alert
return('register') // the same page
//continue with the rest of your code
.....
return ('login-page')
return('register') the same page
如果這解決了您的問題,請不要忘記將此作為正確答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/360209.html
