当提交的表单有效时没有问题,但是当提交的表单无效时(例如,在我们的情况下它是空白的)那么is_valid()抛出此异常: (据我所知is_valid()在这种情况下必须返回false)
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/home/sign-up
Django Version: 1.6
Python Version: 3.3.2
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'employer',
'employee',
'home',
'admin',
'django.contrib.admin')
Installed Middleware:
('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:
File "C:\Python33\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Sina-PC\PycharmProjects\ـ\home\views.py" in sign_up
32. if myForm.is_valid():
File "C:\Python33\lib\site-packages\django\forms\forms.py" in is_valid
129. return self.is_bound and not bool(self.errors)
File "C:\Python33\lib\site-packages\django\forms\forms.py" in errors
121. self.full_clean()
File "C:\Python33\lib\site-packages\django\forms\forms.py" in full_clean
273. self._clean_fields()
File "C:\Python33\lib\site-packages\django\forms\forms.py" in _clean_fields
288. value = field.clean(value)
File "C:\Python33\lib\site-packages\django\forms\fields.py" in clean
149. self.validate(value)
File "C:\Python33\lib\site-packages\django\forms\fields.py" in validate
125. raise ValidationError(self.error_messages['required'], code='required')
Exception Type: TypeError at /home/sign-up
Exception Value: string indices must be integers
我的表格是:
__author__ = 'Sina-PC'
from django import forms
class SignupForm(forms.Form):
username=forms.CharField(max_length=10,widget=forms.TextInput);
username.label='نام کاربری';
username.required=True;
username.error_messages="kkkkkk";
我的观点功能是:
def sign_up(request):
if (request.method=="POST"):
myForm=SignupForm(request.POST);
if myForm.is_valid():
print("do");
return render(request,'home/signup-success.html',{'form':myForm});
myForm=SignupForm();
return render(request,'home/sign-up.html',{'form':myForm});
我的模板是:
<form method="POST" action="{% url 'sign-up' %}">
{% csrf_token %}
<div id="form1" >
{{ form.as_p }}
</div>
<button type="submit" class="btn btn-primary pull-left " style="font-family: tahoma" id="registerBt" >
مرحله بعد
</button>
<div class="clearfix"></div>
</form>
编辑:完全跟踪补充。
答案 0 :(得分:1)
问题在于这一行:username.error_messages="kkkkkk"
。 error_messages
需要dict
,如下所示:
username.error_messages = {'required': 'username is required'}