我不明白如何在模板中返回错误。
I使检查在我的from中有效这看起来像是小错误,但我尝试了不同的变量,但我无法解决这个问题
FORMS.py
class UserForm(forms.Form):
first_name= forms.CharField(max_length=20, label='Name')
last_name= forms.CharField(max_length=20, label='Last_name')
password= forms.CharField(label='Password')
repassword= forms.CharField(label='Confirm password')
def clean(self):
cleaned_data = super().clean()
self.password = cleaned_data('password')
self.repassword = cleaned_data('repassword')
if self.password != self.repassword:
raise ValidationError('Password dont match')
这是我的视图代码我试图验证在def索引和有相同的错误
VIEWS.py
def index(request):
form = UserForm()
if request.method == 'POST':
form = UserForm(request.POST or None)
if form.is_valid():
firstname= form.cleaned_data.get("first_name")
lastname= form.cleaned_data.get("last_name")
password = form.cleaned_data.get('password')
re_password = form.cleaned_data.get('repassword')
form = UserForm()
context = {'form': form,
}
return render(request, 'create_users/index.html', context)
return render(request, 'create_users/index.html', {'form': form}
作为结果,我看到这个更新我的模板
这是模板
的一部分模板
<form action="{% url 'create_users:add_user' %}" method="POST">
{% csrf_token %}
{% for field in form %}
<div class="mb-3">
{{ field }}
</div>
{% for error in field.errors %}
<div class="alert alert-danger">{{error}}</div>
{% endfor %}
{% endfor %}
<button class="btn btn-primary d-block w-100" type="submit" style="--bs-primary: #7286a4;--bs-primary-rgb: 114,134,164;background: rgb(100,105,113);">Create</button>
</form>
和最后的错误消息<<strong>回溯/strong>
Environment:
Request Method: POST
Django Version: 4.1.5
Python Version: 3.11.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'create_users.apps.CreateUsersConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:DevrouterOSenvLibsite-packagesdjangocorehandlersexception.py", line 55, in inner
response = get_response(request)
File "C:DevrouterOSenvLibsite-packagesdjangocorehandlersbase.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:DevrouterOSadmin_consolecreate_usersviews.py", line 13, in index
if form.is_valid():
File "C:DevrouterOSenvLibsite-packagesdjangoformsforms.py", line 205, in is_valid
return self.is_bound and not self.errors
File "C:DevrouterOSenvLibsite-packagesdjangoformsforms.py", line 200, in errors
self.full_clean()
File "C:DevrouterOSenvLibsite-packagesdjangoformsforms.py", line 438, in full_clean
self._clean_form()
File "C:DevrouterOSenvLibsite-packagesdjangoformsforms.py", line 459, in _clean_form
cleaned_data = self.clean()
File "C:DevrouterOSadmin_consolecreate_usersforms.py", line 26, in clean
self.password = cleaned_data('password')
Exception Type: TypeError at /create_users/
Exception Value: 'dict' object is not callable
您的clean
方法有语法错误。
def clean(self):
cleaned_data = super().clean()
# self.password = cleaned_data('password')
self.password = cleaned_data.get('password')
# self.repassword = cleaned_data('repassword')
self.repassword = cleaned_data.get('repassword')
if self.password != self.repassword:
raise ValidationError('Password dont match')
另外,请记住有两种方法来验证表单中的字段:
clean
方法-当有两个或多个相互依赖的字段需要验证时应使用clean_<field_name>
方法-单场清洁方法
这很重要,因为这两个方法的错误存储方式不同。clean_<field_name>
方法将错误存储在您在HTML中正确呈现的form.errors
字典中。但是,clean
方法将错误存储在form.non_field_errors
中。为了呈现这些,我建议在表单代码上方添加这一行:
<form action="{% url 'create_users:add_user' %}" method="POST">
{% csrf_token %}
{# Renders errors reported in clean method #}
{{ form.non_field_errors }}
{% for field in form %}
<div class="mb-3">
{{ field }}
</div>
{% for error in field.errors %}
<div class="alert alert-danger">{{error}}</div>
{% endfor %}
{% endfor %}
...
</form>
最后一件事
我在你的视图代码中发现一些问题。我将在下面添加一个注释版本的代码:
def index(request):
form = UserForm()
if request.method == 'POST':
form = UserForm(request.POST or None)
if form.is_valid():
firstname= form.cleaned_data.get("first_name")
lastname= form.cleaned_data.get("last_name")
password = form.cleaned_data.get('password')
re_password = form.cleaned_data.get('repassword')
# DON'T override the form here. If the form is invalid
# you want to re-render that exact form instance because
# it will contain the errors
# form = UserForm()
context = {'form': form}
# If the form is valid, you want to redirect to the success page
# See this antipattern: https://www.django-antipatterns.com/antipattern/rendering-content-after-a-successful-post-request.html
return render(request, 'create_users/index.html', context)
return render(request, 'create_users/index.html', {'form': form}