所以......我一直在敲打这个问题。尝试验证表单时,我遇到了最奇怪的错误。我将输入传递给想要在表单验证失败时测试行为的表单,即我希望它验证失败。
我有一个表格的代码:
class CTAForm(forms.Form):
first_name = forms.CharField(max_length=50)
email = forms.EmailField()
phone = forms.CharField(max_length=15, required=False, label='Phone (optional)')
我在视图中的某个地方进行此调用以处理表单数据。
if cta_form.is_valid():
我得到:
Exception Type: TypeError
Exception Value: 'str' object is not callable
Exception Location: /usr/lib/pymodules/python2.6/django/forms/forms.py in full_clean, line 246
Traceback显示了这一点:
/usr/lib/pymodules/python2.6/django/forms/forms.py 在full_clean:
- 除了ValidationError,e:
- self._errors [name] = self.error_class(e.messages)...
醇>▼本地变量
变量值
e:ValidationError()
字段:django.forms.fields.EmailField对象位于< 0x225c4d0c>
名称:'电子邮件'
self:blah.views.CTAForm对象位于< 0x2245b42c>
价值:你''
我感觉很愚蠢。有人在这个问题上给我提供指导吗?感谢。
编辑:按要求提供更完整的观看代码
def cta_add(request):
context_dict = {'categories': Category.objects.all().order_by('order'),}
# we always expect to receive data via post
if request.method =='POST':
# get the current vid based on the parameter
current_vid = Video.objects.get(slug=request.POST['current_vid'])
# use this video to create our dynamic form so we get the valid cta values based on that video
cta_form_class = make_cta_form(current_vid.cta_set.all().order_by('order'))
# instantiate our new dynamic form based on the post data
cta_form = cta_form_class(request.POST, error_class='error')
# if we got this far, we were able to generate a form to validate the user's input against.
# If form validates, than process and take user to success screen
if cta_form.is_valid():
辅助函数make_cta_form在下面
def make_cta_form(cta_set):
cta_list =[]
if not cta_set is None:
for cta in cta_set:
cta_list.append((cta.text, cta.text))
class CTAForm(forms.Form):
cta = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=cta_list, label='', required=False)
first_name = forms.CharField(max_length=50)
email = forms.EmailField()
phone = forms.CharField(max_length=15, required=False, label='Phone (optional)')
return CTAForm
答案 0 :(得分:1)
您收到有关字符串不可调用的错误,但您的表单的错误类是字符串,而不是错误类。
cta_form = cta_form_class(request.POST, error_class='error')
现在我在error_class中找到的文档中唯一的引用是作为字符串列表,所以你可以试试
cta_form = cta_form_class(request.POST, error_class=['error'])
虽然做一些像
这样的事情似乎更有意义 import forms
[...]
cta_form = cta_form_class(request.POST, error_class=forms.ValidationError("error"))
或可能:
cta_form = cta_form_class(request.POST, error_class=forms.ValidationError)
答案 1 :(得分:0)
在您的views.py
文件中。当你得到表格(用户填写后)。这是你做的吗?
from your_app.forms import *
def process_form(request):
cta_form = CTAForm(request.POST)
if cta_form.is_valid():
# your code.
您需要将表单的POST作为构造函数的初始值传递。