Ошибки пользовательской регистрационной формы Django
Надеюсь, у вас будет прекрасный день.
Я создал пользовательскую форму регистрации, но когда форма не действительна, форма возвращается без ошибки на ней.
Пример:
Я вставляю неправильный пароль во вход "confirm password", и после отправки формы, на самой форме не было найдено никакой ошибки.
Возможно, это потому, что я неправильно возвращаю форму?
Это мой файл 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})
есть много других мест, где вы делаете то же самое (форма с данными request.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()
do:
pro = Profile.objects.create(user=user, isVerified=False)