希望你有美好的一天。
我已經構建了自定義注冊表單,但是當表單無效時,該表單會回傳而沒有錯誤。
例子:
我輸入了錯誤的密碼來“確認密碼”輸入,發送表單后,表單本身沒有發現錯誤。
可能是因為我沒有正確回傳表格?
這是我的 form.py 檔案:
class SignUpForm(UserCreationForm):
email = forms.EmailField(max_length=50, help_text='Required. Inform a valid email address.',
widget=(forms.TextInput(attrs={'class': 'form-control'})))
password1 = forms.CharField(label=('Password'),
widget=(forms.PasswordInput(
attrs={'class': 'form-control'})),
help_text=password_validation.password_validators_help_text_html())
password2 = forms.CharField(label=('Password Confirmation'), widget=forms.PasswordInput(attrs={'class': 'form-control'}),
help_text=('Just Enter the same password, for confirmation'))
username = forms.CharField(
label=('Username'),
max_length=150,
help_text=(
'Required. 150 characters or fewer. Letters, digits and @/./ /-/_ only.'),
error_messages={'unique': (
"A user with that username already exists.")},
widget=forms.TextInput(attrs={'class': 'form-control'})
)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2',)
使用注冊表單的注冊功能:
csrf_exempt
def signup1(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid() is False:
form = SignUpForm()
return render(request, 'accounts/register.html', {'form': form})
if form.is_valid():
print(str(form.cleaned_data["email"]))
email = str(form.cleaned_data["email"])
username = str(form.cleaned_data["username"])
p1 = str(form.cleaned_data["password1"])
p2 = str(form.cleaned_data["password2"])
try:
user1 = User.objects.get(email__exact=email)
except:
form = SignUpForm()
return render(request, 'accounts/register.html', {'form': form})
if p1 != p2:
form = SignUpForm()
return render(request, 'accounts/register.html', {'form': form})
user = User.objects.create_user(
email=email, username=username, password=p1)
print("EMAIL? " str(user.email))
user.refresh_from_db()
# load the profile instance created by the signal
user.save()
pro = Profile(user_id=user.id, isVerified=False)
pro.save()
sender = '[email protected]'
receiver = [str(user.email)]
message = "Welcome to XIL Platform " receiver[0] \
" Please Verify you account by clicking \n the link in the email we sent you! \n" \
"If you registerd in heroku use this link to verify - https://django.herokuapp.com//verifyAccount?email=" receiver[0] \
"\n If you are using localhost use this link to verify - http://localhost:8000/verifyAccount?email=" \
receiver[0]
try:
# send your message with credentials specified above
with smtplib.SMTP(smtp_server, port) as server:
server.starttls()
server.login(loginAddr, password)
server.sendmail(sender, receiver, message)
return redirect('/')
# tell the script to report if your message was sent or which errors need to be fixed
print('Sent')
return redirect('/')
except (gaierror, ConnectionRefusedError):
print('Failed to connect to the server. Bad connection settings?')
except smtplib.SMTPServerDisconnected:
print('Failed to connect to the server. Wrong user/password?')
except smtplib.SMTPException as e:
print('SMTP error occurred: ' str(e))
return redirect('/')
else:
return render(request, 'accounts/register.html', {'form': form})
return render(request, 'accounts/register.html', {'form': form})
當然還有 HTML 檔案。
<form action="/signup" method="post">
{% csrf_token %}
<form method="post">
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }}<br>
{{ field }}
{% if field.help_text %}
<small style="color: grey">{{ field.help_text | safe }}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error | safe }}</p>
{% endfor %}
</p>
{% endfor %}
</div>
<div class="card-footer">
<button type="submit" onclick="" class="btn btn-primary">Register</button>
Have an account? <a href="{% url 'login' %}" class="text-primary">Login</a>
</div>
</form>
uj5u.com熱心網友回復:
當表單無效時,您正在清除表單
form = SignUpForm(request.POST)
if form.is_valid() is False:
form = SignUpForm() # <== e.g. here (remove this line)
return render(request, 'accounts/register.html', {'form': form})
還有許多其他地方可以做同樣的事情(帶有 request.POST 資料的表單包含錯誤。
此外,bareexcept:會隱藏錯誤,我會認真考慮重構這個視圖。很多代碼應該在表單的 clean/is_valid 函式中(例如查看 django.contrib.auth 用戶創建表單:https : //github.com/django/django/blob/main/django/contrib/ auth/forms.py#L109 )
我還敦促您拼寫 is-not-valid 檢查:
if not form.is_valid():
而不是:
pro = Profile(user_id=user.id, isVerified=False)
pro.save()
做:
pro = Profile.objects.create(user=user, isVerified=False)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/316238.html
上一篇:無法將引數型別“Pattern”分配給引數型別“String”?
下一篇:我正在嘗試使用postgresql創建檢查登錄程序,如果密碼已經存在,那么它應該回傳1else0。SQL查詢如下
