祝你度过美好的一天。
我已经建立了自定义注册表单,但是当表单无效时,表单返回没有错误。
的例子:
我在"确认密码"中插入了错误的密码。输入,并且在发送表单后,表单本身没有发现任何错误。
这可能是因为我没有正确返回表单?
这是我的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',)
使用signup表单的注册函数:
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 = 'xilplatform@gmail.com'
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>
当表单无效时,您将清除该表单
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})
还有许多其他地方可以使用相同的方法(将表单与请求结合起来)。POST数据包含错误。
此外,裸except:
将隐藏错误,我会认真考虑重构这个视图。许多代码应该在表单的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)