为什么我的django表格一直在说“需要此字段”。
我是Django的初学者。我的注册页面使我的表格无效,即使两个密码字段都填充并且它们相同,它也会不断打印相同的错误。我只附加了与密码字段错误相关的任何代码
:< ul class =“ errorList”>< li&gt password1&lt class1&lt class =“ errorlist” 。 ;;/li>< li> __ all __< ul class =“ errorlist nonfield”> gt;< li> li不匹配。代码>
forms.py:views.py(in
class RegisterForm(UserCreationForm):
password1 = forms.CharField(
required=True,
widget=forms.PasswordInput(attrs={
'class': 'form-control',
'name': 'password1',
'id': 'floatingPassword',
'placeholder':'Password',
}),
)
password2 = forms.CharField(
required=True,
widget=forms.PasswordInput(attrs={
'class': 'form-control',
'name': 'password2',
'id': 'floatingConfirmPassword',
'placeholder':'Confirm password',
}),
)
class Meta:
model = User
fields = [
'password1',
'password2',
]
# Compare password
def clean(self):
self.cleaned_data = super().clean()
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password != password2:
raise forms.ValidationError("Passwords do not match.")
return self.cleaned_data
Prototype)
def register(request):
# Create a new form
if request.method == 'GET':
form = RegisterForm()
return render(request, 'users/register.html', {'form': form})
# When the user submits the form
elif request.method == 'POST':
form = RegisterForm(request.POST)
# Check if the form is valid
if form.is_valid():
print('FORM is valid!')
print(form.cleaned_data)
form.save()
#user = form.cleaned_data.get('username')
#messages.success(request, f"Account has been created for {user}")
# UPDATE THE URL LINK IN THE FUTURE
return redirect('/login')
else:
print('Form is not valid')
print(form.errors)
#messages.error(request, 'Error processing your request')
return render(request, 'users/register.html', {'form': form})
register.html:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, inital-scale=1.0">
<!--Load bootstrap library-->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<title>Sign Up | Portfolio</title>
</head>
<body>
<div class="container">
<form class="needs-validation" novalidate method="POST">
{% csrf_token %}
<div class="row g-2 col-md-12 mb-3">
<div class="form-floating col-md-6">
{{ form.password1 }}
<label for="floatingPassword" class="form-label">Password</label>
<div class="valid-feedback"></div>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="form-floating col-md-6">
{{ form.password2 }}
<label for="floatingConfirmPassword" class="form-label">Enter password again</label>
<div class="valid-feedback"></div>
<div class="invalid-feedback">
Enter the password again.
</div>
</div>
<div class="col-12 text-center">
<button class="btn btn-success btn.lg" type="submit">Sign Up</button>
</div>
</div>
</form>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
</script>
</div>
</body>
</html>
I'm a beginner at Django. My registration page is making my form invalid and it keeps printing the same error even though both the password fields are filled and they are the same. I have only attached any codes that are relevant to the password fields
Error: <ul class="errorlist"><li>password1<ul class="errorlist"><li>This field is required.</li></ul></li><li>password2<ul class="errorlist"><li>This field is required.</li></ul></li><li>__all__<ul class="errorlist nonfield"><li>Passwords do not match.</li></ul></li></ul>
forms.py:
class RegisterForm(UserCreationForm):
password1 = forms.CharField(
required=True,
widget=forms.PasswordInput(attrs={
'class': 'form-control',
'name': 'password1',
'id': 'floatingPassword',
'placeholder':'Password',
}),
)
password2 = forms.CharField(
required=True,
widget=forms.PasswordInput(attrs={
'class': 'form-control',
'name': 'password2',
'id': 'floatingConfirmPassword',
'placeholder':'Confirm password',
}),
)
class Meta:
model = User
fields = [
'password1',
'password2',
]
# Compare password
def clean(self):
self.cleaned_data = super().clean()
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password != password2:
raise forms.ValidationError("Passwords do not match.")
return self.cleaned_data
views.py (In prototype)
def register(request):
# Create a new form
if request.method == 'GET':
form = RegisterForm()
return render(request, 'users/register.html', {'form': form})
# When the user submits the form
elif request.method == 'POST':
form = RegisterForm(request.POST)
# Check if the form is valid
if form.is_valid():
print('FORM is valid!')
print(form.cleaned_data)
form.save()
#user = form.cleaned_data.get('username')
#messages.success(request, f"Account has been created for {user}")
# UPDATE THE URL LINK IN THE FUTURE
return redirect('/login')
else:
print('Form is not valid')
print(form.errors)
#messages.error(request, 'Error processing your request')
return render(request, 'users/register.html', {'form': form})
register.html:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, inital-scale=1.0">
<!--Load bootstrap library-->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<title>Sign Up | Portfolio</title>
</head>
<body>
<div class="container">
<form class="needs-validation" novalidate method="POST">
{% csrf_token %}
<div class="row g-2 col-md-12 mb-3">
<div class="form-floating col-md-6">
{{ form.password1 }}
<label for="floatingPassword" class="form-label">Password</label>
<div class="valid-feedback"></div>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="form-floating col-md-6">
{{ form.password2 }}
<label for="floatingConfirmPassword" class="form-label">Enter password again</label>
<div class="valid-feedback"></div>
<div class="invalid-feedback">
Enter the password again.
</div>
</div>
<div class="col-12 text-center">
<button class="btn btn-success btn.lg" type="submit">Sign Up</button>
</div>
</div>
</form>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
</script>
</div>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论