I'm happy to submit a ticket but wanted to check first that I'm doing
the right thing. I think this used to work in Django 1.1 but not now
in trunk.
I can better explain it with code:
# models.py
class FooBarModel(models.Model):
name = models.CharField(max_length=10)
age = models.IntegerField()
user = models.ForeignKey(User)
# forms.py
class FooBarForm(forms.ModelForm):
class Meta:
model = FooBarModel
def __init__(self, *a, **k):
super(FooBarForm, self).__init__(*a, **k)
for field in self.fields:
self.fields[field].required = False
The point of this is that I can make an advanced search form where the
form is just like the form for added one of these models. In my view I
never call the save() method of the form instance.
# tests.py
class SimpleTest(TestCase):
def test_model_forms(self):
from forms import FooBarForm
post = {'name':'Peter'}
f2 = FooBarForm(data=post)
self.assertTrue(not f2.is_valid())
Instead of returning False on the is_valid() function, it raises a
ValueError which looks like this:
Traceback (most recent call last):
File "/home/peterbe/dev/DJANGO/lc/debugapp/tests.py", line 14, in
test_model_forms
print f2.is_valid()
File "/home/peterbe/virtualenvs/lc/lib/python2.5/site-packages/
Django-1.2.1-py2.5.egg/django/forms/forms.py", line 121, in is_valid
return self.is_bound and not bool(self.errors)
File "/home/peterbe/virtualenvs/lc/lib/python2.5/site-packages/
Django-1.2.1-py2.5.egg/django/forms/forms.py", line 112, in
_get_errors
self.full_clean()
File "/home/peterbe/virtualenvs/lc/lib/python2.5/site-packages/
Django-1.2.1-py2.5.egg/django/forms/forms.py", line 269, in full_clean
self._post_clean()
File "/home/peterbe/virtualenvs/lc/lib/python2.5/site-packages/
Django-1.2.1-py2.5.egg/django/forms/models.py", line 317, in
_post_clean
self.instance = construct_instance(self, self.instance,
opts.fields, opts.exclude)
File "/home/peterbe/virtualenvs/lc/lib/python2.5/site-packages/
Django-1.2.1-py2.5.egg/django/forms/models.py", line 51, in
construct_instance
f.save_form_data(instance, cleaned_data[
f.name])
File "/home/peterbe/virtualenvs/lc/lib/python2.5/site-packages/
Django-1.2.1-py2.5.egg/django/db/models/fields/__init__.py", line 416,
in save_form_data
setattr(instance,
self.name, data)
File "/home/peterbe/virtualenvs/lc/lib/python2.5/site-packages/
Django-1.2.1-py2.5.egg/django/db/models/fields/related.py", line 314,
in __set__
(instance._meta.object_name,
self.field.name))
ValueError: Cannot assign None: "FooBarModel.user" does not allow null
values.
I can understand that the field doesn't like having None set as a
value because it will never allow the save but I'm not interested in
saving here. I'm interested in getting a form that models (no pun
intended) itself on a model.
So, bug or feature?