======= 更新 =======
使用以下代码,我设法自动为模型的所有字段生成随机数据,除了我想要操作的那些。
tests.py:
from django.db import models
class Man(models.Model):
name = models.CharField(max_length = 12)
age = models.PositiveSmallIntegerField()
models.py
from my_app.models import Man
from django import forms
from django.core.exceptions import ValidationError
class ManForm(forms.ModelForm):
age_verification = forms.IntegerField()
def clean(self):
if not self.cleaned_data['age'] == self.cleaned_data['age_verification']:
raise ValidationError("Is this a LIE?")
class Meta:
model = Man
fields = ['name', 'age', 'age_verification']
forms.py:
from django.test import TestCase
from houses.forms import ManForm
class ModelsTest(TestCase):
def test_Man(self):
data = {
'name' = 'John',
'age' = 20,
'ege_verification' = 20,
}
form = ManForm(data)
暂时,我会这样测试:
tests.py:
{{1}}
是否有工具为Forms提供随机数据? 或者......我可以将available tools用于此目的的模型吗? 搜索那些支持Python 3的人的文档,我不明白如何实现这一点。
唯一明确提供此类服务的是Django-Whatever,它不兼容python3。
答案 0 :(得分:1)
你可以这样做:
from model_mommy import mommy
class ModelsTest(TestCase):
def test_Man(self):
man = mommy.make('Man', _fill_optional=True)
data = {
'name': man.name,
'age': man.age,
'age_verification': man.age_verification,
}
form = ManForm(data)
答案 1 :(得分:1)
如果您不想输入每个属性的名称,可以执行以下操作:
from model_mommy import mommy
from django.forms import model_to_dict
class ModelsTest(TestCase):
def test_Man(self):
man = mommy.make('Man')
data = model_to_dict(man)
form = ManForm(data)