Django 使用 ForeignKey 形成单元测试
Django forms unit tests with ForeignKey
我有一个 ModelForm
,其中包含一些 ForeignKey
,对用户对象说,但它可以对任何其他模型。我对此表单进行了单元测试 class,但是当我尝试向其传递数据时,出现 Select a valid choice. That choice is not one of the available choices
错误。测试看起来像这样:
class Monkey(Model):
user = models.ForeignKey(User)
...
class MyForm(ModelForm):
class Meta:
model = Monkey
fields = ['user', ...]
def test_my_form_with_a_user(self):
...
data = {'user': User.objects.get(pk=1), ... } # Nope.
data = {'user': [u'1'], ... } # Nope.
data = {'user': [u'JaneDoe'], ... } # Nope.
form = MyForm(data, ...)
self.assertTrue(form.is_valid(), form.errors)
...
我已经为 user
尝试了任意数量的排列,但我得到了同样的错误。
我错过了什么?
您应该能够使用以下方法为测试中的用户字段赋值:
def test_my_form_with_a_user(self):
user_pk = User.objects.get(pk=1).pk
data = {'user': user_pk}
...
我有一个 ModelForm
,其中包含一些 ForeignKey
,对用户对象说,但它可以对任何其他模型。我对此表单进行了单元测试 class,但是当我尝试向其传递数据时,出现 Select a valid choice. That choice is not one of the available choices
错误。测试看起来像这样:
class Monkey(Model):
user = models.ForeignKey(User)
...
class MyForm(ModelForm):
class Meta:
model = Monkey
fields = ['user', ...]
def test_my_form_with_a_user(self):
...
data = {'user': User.objects.get(pk=1), ... } # Nope.
data = {'user': [u'1'], ... } # Nope.
data = {'user': [u'JaneDoe'], ... } # Nope.
form = MyForm(data, ...)
self.assertTrue(form.is_valid(), form.errors)
...
我已经为 user
尝试了任意数量的排列,但我得到了同样的错误。
我错过了什么?
您应该能够使用以下方法为测试中的用户字段赋值:
def test_my_form_with_a_user(self):
user_pk = User.objects.get(pk=1).pk
data = {'user': user_pk}
...