我目前正在处理的系统需要用户在注册时输入两个紧急联系号码。我想实现一个确保用户输入有效数字的检查,我确定这是一个以0或+开头的字符串。为此,我尝试覆盖表单中的clean方法,但它不能正常工作。
这是我的相关方法的forms.py代码(现在更新,抛出下面说明的错误。):
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('emergcon1', 'emergcon2')
labels = {
'emergcon1': ('Emergency Contact Number'),
'emergcon2': ('Emergency Contact Number 2')
}
def clean_emergcon1(self):
emergcon1 = self.cleaned_data['emergcon1']
print emergcon1
if emergcon1[:1] != '0' or '+':
raise ValidationError(
_('%(emergcon1)s is not a valid phone number'),
params={'emergcon1': emergcon1},
)
return emergcon1
def clean_emergcon2(self):
emergcon2 = self.cleaned_data.['emergcon2']
if emergcon2[:1] != '0' or '+':
raise ValidationError(
_('%(emergcon2)s is not a valid phone number'),
params={'emergcon2': emergcon2},
)
return emergcon2
views.py: def注册(请求): registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
registered = True
else:
print(user_form.errors, profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render(request, 'tennis/register.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered})
models.py:
class UserProfile(models.Model):
user = models.OneToOneField(User)
emergcon1 = models.CharField(max_length=128, blank=False)
emergcon2 = models.CharField(max_length=128, blank=False)
def _unicode_(self):
return self.user.username
return self.emergcon1
return self.emergcon2
我的register.html:
{% extends 'tennis/base.html' %}
{% load staticfiles %}
{% block body_block%}
{% block title_block %}
Registration
{% endblock %}
<body>
<h1>Register Here</h1>
{% if registered %}
<strong> Thank you for registering</strong>
<a href="{% url 'index' %}"> Return to homepage </a><br />
{% else %}
<form id="user_form" method="post" action="{% url 'register' %}">
{% csrf_token %}
<!-- displays forms -->
{{ user_form.as_p }}
{{ profile_form.as_p }}
<!-- adds submit button -->
<input type="submit" name="submit" value="Register" />
</form>
{% endif %}
</body>
{% endblock %}
完整错误追溯,错误全局名称&#39; _&#39;未定义:
Internal Server Error: /tennis/register/
Traceback (most recent call last):
File "/home/steph/.virtualenvs/tennis/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/steph/.virtualenvs/tennis/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/steph/Documents/project/tennis_system_project/tennis/views.py", line 29, in register
if user_form.is_valid() and profile_form.is_valid():
File "/home/steph/.virtualenvs/tennis/local/lib/python2.7/site-packages/django/forms/forms.py", line 161, in is_valid
return self.is_bound and not self.errors
File "/home/steph/.virtualenvs/tennis/local/lib/python2.7/site-packages/django/forms/forms.py", line 153, in errors
self.full_clean()
File "/home/steph/.virtualenvs/tennis/local/lib/python2.7/site-packages/django/forms/forms.py", line 362, in full_clean
self._clean_fields()
File "/home/steph/.virtualenvs/tennis/local/lib/python2.7/site-packages/django/forms/forms.py", line 383, in _clean_fields
value = getattr(self, 'clean_%s' % name)()
File "/home/steph/Documents/project/tennis_system_project/tennis/forms.py", line 30, in clean_emergcon1
_('%(emergcon1)s is not a valid phone number'),
NameError: global name '_' is not defined
已解决,用&#34;导入从django.utils.translation导入ugettext_lazy为_&#34;
新问题:以0开头的数字未被识别为有效。我提供了07896428317,当我点击提交时,它给了我&#34; 07896428317不是有效的电话号码&#34;。
答案 0 :(得分:0)
由于在clean()
方法内部待验证的字段不依赖于彼此,您可以像这样重写逻辑,即使用clean_<field_name>
方法:
from django.utils.translation import ugettext_lazy as _
class UserProfileForm(forms.ModelForm):
class Meta:
# as is
def clean_emergcon1(self):
""" Validation of emergcon1 specifically """
emergcon1 = self.cleaned_data['emergcon1']
if emergcon1[:1] not in ['0', '+']:
raise ValidationError(
_('%(emergcon1)s is not a valid phone number'),
params={'emergcon1': emergcon1},
)
# Always return a value to use as the new cleaned data, even if
# this method didn't change it.
return emergcon1
def clean_emergcon2(self):
""" Validation of emergcon2 specifically """
emergcon2 = self.cleaned_data['emergcon2']
if emergcon2[:1] not in ['0', '+']:
raise ValidationError(
_('%(emergcon2)s is not a valid phone number'),
params={'emergcon2': emergcon2},
)
# Always return a value to use as the new cleaned data, even if
# this method didn't change it.
return emergcon2