form.is_valid()在Django单元测试中失败
我正在为Django表单运行单元测试,form.is_valid()在Django单元测试中失败,django,django-forms,django-testing,django-unittest,django-tests,Django,Django Forms,Django Testing,Django Unittest,Django Tests,我正在为Django表单运行单元测试,form.is\u valid()不断返回False,我找不到错误 下面是forms.py的代码: class CustomClearableFileInput(forms.ClearableFileInput): template_name = 'forums/templates/clearable_file_input.html' class NewQuestionForm(forms.ModelForm): category = f
form.is\u valid()
不断返回False
,我找不到错误
下面是forms.py的代码:
class CustomClearableFileInput(forms.ClearableFileInput):
template_name = 'forums/templates/clearable_file_input.html'
class NewQuestionForm(forms.ModelForm):
category = forms.ModelChoiceField(widget = forms.Select(attrs = {}),
queryset = FossCategory.objects.order_by('name'),
empty_label = "Select a Foss category",
required = True,
error_messages = {'required':'Select a category'})
title = forms.CharField(widget = forms.TextInput(),
required = True,
error_messages = {'required':'Title field required'},
strip=True)
body = forms.CharField(widget = forms.Textarea(),
required = True,
error_messages = {'required':'Question field required'},
strip=True)
is_spam = forms.BooleanField(required = False)
spam_honeypot_field = HoneypotField()
image = forms.ImageField(widget = CustomClearableFileInput(), help_text = "Upload image", required = False)
def clean_title(self):
title = str(self.cleaned_data['title'])
if title.isspace():
raise forms.ValidationError("Title cannot be only spaces")
if len(title) < 12:
raise forms.ValidationError("Title should be longer than 12 characters")
if Question.objects.filter(title = title).exists():
raise forms.ValidationError("This title already exist.")
return title
def clean_body(self):
body = str(self.cleaned_data['body'])
if body.isspace():
raise forms.ValidationError("Body cannot be only spaces")
if len(body) < 12:
raise forms.ValidationError("Body should be minimum 12 characters long")
body = body.replace(' ', ' ')
body = body.replace('<br>', '\n')
return body
class Meta(object):
model = Question
fields = ['category', 'title', 'body', 'is_spam', 'image']
这是我通过打印(form.errors)
得到的:
- 类别
- 选择有效选项。该选项不是可用选项之一。
由于它是一个模型选择字段,请尝试使用类别的主键,而不是实例本身
form = NewQuestionForm(data = {'category': category.pk, 'title': title, 'body': 'Test question body'})
检查
form.errors
以查看其无效原因。我已用收到的错误更新了我的问题。我意识到了我的错误,并准备添加答案,但是的,这就是问题所在。非常感谢!:)
<ul class="errorlist"><li>category<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li>
form = NewQuestionForm(data = {'category': category.pk, 'title': title, 'body': 'Test question body'})