======= Update =======
@JF brought forward a brilliant perspective for the use of model mommy in ModelForms.
With the following code, I managed to automatically generate random data for all the fields of the model, except for the ones I would like to manipulate.
tests.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())
models.py
from django.db import models
class Man(models.Model):
name = models.CharField(max_length = 12)
age = models.PositiveSmallIntegerField()
forms.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']
For the time being, I test it like this:
tests.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)
Is there a tool that provides random data for Forms? Or ... can I use the available tools for models for this purpose? Searching the docs of those supporting Python 3, I did not understand how this could be achieved.
The only one that clearly provides such a service is Django-Whatever which is not python3 compatible.
You could do something like this:
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)