0

=======更新=======

@JF 为在 ModelForms 中使用模型妈妈提出了一个绝妙的视角。

使用以下代码,我设法为模型的所有字段自动生成随机数据,除了我想要操作的那些。

测试.py:

from django.test import TestCase
from houses.forms import ManForm
from houses.models import Man

class ModelsTest(TestCase):

    def test_Man(self):
        man = mommy.make('Man', age=20)
        data = {each_field.name: getattr(man, each_field.name) for each_field in man._meta.fields}
        data.update({'age_verification': 20})
        form = ManForm(data)
        self.assertTrue (form.is_valid())

模型.py

from django.db import models

class Man(models.Model):
    name = models.CharField(max_length = 12)
    age = models.PositiveSmallIntegerField()

表格.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']    

暂时,我这样测试它:

测试.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)

是否有为表单提供随机数据的工具?或者......我可以为此目的使用模型的可用工具吗?搜索那些支持 Python 3 的文档,我不明白这是如何实现的。

唯一明确提供此类服务的是Django-Whatever,它与 python3 不兼容。

4

2 回答 2

2

如果您不想键入每个属性的名称,可以这样做:

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)
于 2016-10-31T14:29:45.227 回答
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)
于 2015-09-13T14:47:41.783 回答