即使强悍的输入有效,有关表单验证的Django TestCase也会失败

时间:2019-01-23 20:47:19

标签: python django django-forms django-testing

如标题中所述,当我使用FormView时,我有一个可以正确验证的表格。但是,当我今天开始写测试时  在TestCase中,相同的输入失败,并且出现以下错误:

{'programming_language': ['Select a valid choice. That choice is not one of the available choices.']}

这些是我正在使用的模型,表格,视图和测试

# models.py
from django.db import models


class Tag(models.Model):

    name = models.CharField(max_length=40, unique=True)

class ProgrammingLanguage(models.Model):

    name = models.CharField(max_length=40, unique=True)

class Snippet(models.Model):

    title = models.CharField(max_length=40)
    programming_language = models.ForeignKey(ProgrammingLanguage, on_delete=models.CASCADE)
    creation_date = models.DateTimeField(auto_now_add=True)
    explanation = models.TextField()
    code = models.TextField()
    tags = models.ManyToManyField(Tag)


# forms.py  
from django import forms
from django.utils.translation import gettext_lazy as _

from .models import Snippet

class SnippetForm(forms.ModelForm):

    class Meta:
        model = Snippet
        exclude = ["creation_date"]

# views.py
from django.urls import reverse_lazy
from django.views import generic
from .models import Snippet
from .forms import SnippetForm

class SnippetFormView(generic.FormView):
    template_name = "snippets/snippet_form.html"
    form_class = SnippetForm
    success_url = reverse_lazy("snippets")

    def form_valid(self, form):
        # for testing purposes
        print(form.cleaned_data)
        form.save()
        return super().form_valid(form)

# test_forms.py
from django.test import TestCase

from snippets.forms import SnippetForm
from snippets.models import ProgrammingLanguage, Tag, Snippet

class SnippetFormTestCase(TestCase):

    @classmethod
    def setUpTestData(cls):
        ProgrammingLanguage.objects.create(name="Javascript")
        Tag.objects.create(name="website")

    def test_forms(self):
        form = SnippetForm({
            'title': 'Test snippet title',
            'programming_language': ProgrammingLanguage.objects.get(pk=1),
            'code': 'code here',
            'explanation': 'explanation here',
            'tags': Tag.objects.all()
        })
        # calling is valid to get cleaned_data and original data 
        form.is_valid()
        print(form.data)
        print(form.cleaned_data)
        self.assertEqual(form.errors, {})

这是我在视图中看到的cleaned_data

{'title': 'Test snippet title', 'programming_language': <ProgrammingLanguage: Javascript>, 'explanation': 'explanation here', 'code': 'code here', 'tags': <QuerySet [<Tag: website>]>}

这是我在测试中得到的数据和cleaned_data:

# data
{'title': 'Test snippet title', 'programming_language': <ProgrammingLanguage: Javascript>, 'code': 'code here', 'explanation': 'explanation here', 'tags': <QuerySet [<Tag: website>]>}
# cleaned_data
{'title': 'Test snippet title', 'explanation': 'explanation here', 'code': 'code here', 'tags': <QuerySet [<Tag: website>]>}

为什么在测试过程中,ProgrammingLanguage是无效的选择,而在使用网站时却有效?

1 个答案:

答案 0 :(得分:0)

在测试中尝试一下:

form = SnippetForm({
        'title': 'Test snippet title',
        'programming_language': 1, #ProgrammingLanguage.objects.get(pk=1),
        'code': 'code here',
        'explanation': 'explanation here',
        'tags': Tag.objects.all()
    })

在将具有主键作为其字段之一的模型使用表单时,使用该字段的pk值(而不是模型实例)将表单绑定到数据。

FormView就是这样。这就是为什么视图正常运行时测试失败的原因。

还要确保您使用pk为1的编程语言。