Skip to content

Commit

Permalink
Fixed #10405 -- Raise a more useful error if the formfield of a relat…
Browse files Browse the repository at this point in the history
…ed model field can't be created yet because the related model isn't loaded yet. Thanks ojii and charstring.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16604 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
jezdez committed Aug 12, 2011
1 parent 386b12c commit 1d485cf
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
2 changes: 1 addition & 1 deletion django/core/exceptions.py
Expand Up @@ -3,7 +3,7 @@
"""

class DjangoRuntimeWarning(RuntimeWarning):
pass
pass

class ObjectDoesNotExist(Exception):
"The requested object does not exist"
Expand Down
4 changes: 4 additions & 0 deletions django/db/models/fields/related.py
Expand Up @@ -905,6 +905,10 @@ def contribute_to_related_class(self, cls, related):

def formfield(self, **kwargs):
db = kwargs.pop('using', None)
if isinstance(self.rel.to, basestring):
raise ValueError("Cannot create form field for %r yet, because "
"its related model %r has not been loaded yet" %
(self.name, self.rel.to))
defaults = {
'form_class': forms.ModelChoiceField,
'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to),
Expand Down
33 changes: 33 additions & 0 deletions tests/regressiontests/forms/tests/models.py
@@ -1,7 +1,9 @@
# -*- coding: utf-8 -*-
import datetime
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import models
from django.forms import Form, ModelForm, FileField, ModelChoiceField
from django.forms.models import ModelFormMetaclass
from django.test import TestCase
from regressiontests.forms.models import (ChoiceOptionModel, ChoiceFieldModel,
FileModel, Group, BoundaryModel, Defaults)
Expand Down Expand Up @@ -160,3 +162,34 @@ class Meta:
self.assertEqual(obj.name, u'class default value')
self.assertEqual(obj.value, 99)
self.assertEqual(obj.def_date, datetime.date(1999, 3, 2))

class RelatedModelFormTests(TestCase):
def test_invalid_loading_order(self):
"""
Test for issue 10405
"""
class A(models.Model):
ref = models.ForeignKey("B")

class Meta:
model=A

self.assertRaises(ValueError, ModelFormMetaclass, 'Form', (ModelForm,), {'Meta': Meta})

class B(models.Model):
pass

def test_valid_loading_order(self):
"""
Test for issue 10405
"""
class A(models.Model):
ref = models.ForeignKey("B")

class B(models.Model):
pass

class Meta:
model=A

self.assertTrue(issubclass(ModelFormMetaclass('Form', (ModelForm,), {'Meta': Meta}), ModelForm))

0 comments on commit 1d485cf

Please sign in to comment.