From ef889d5b10c02c8f0c19f7384fbb51d291240bee Mon Sep 17 00:00:00 2001 From: Morgan Aubert Date: Wed, 14 Dec 2016 14:04:26 -0500 Subject: [PATCH] Fixed #27599 -- Fixed Field.__str__() crash for fields not attached to models. --- django/db/models/fields/__init__.py | 7 ++++++- tests/model_fields/tests.py | 5 +++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index 340e6a41b7..f1f68dbe7a 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -186,7 +186,12 @@ class Field(RegisterLookupMixin): self.error_messages = messages def __str__(self): - """ Return "app_label.model_label.field_name". """ + """ + Return "app_label.model_label.field_name" for fields attached to + models. + """ + if not hasattr(self, 'model'): + return super(Field, self).__str__() model = self.model app = model._meta.app_label return '%s.%s.%s' % (app, model._meta.object_name, self.name) diff --git a/tests/model_fields/tests.py b/tests/model_fields/tests.py index f7faf399c7..5869196335 100644 --- a/tests/model_fields/tests.py +++ b/tests/model_fields/tests.py @@ -1,7 +1,6 @@ from django import forms from django.db import models from django.test import SimpleTestCase, TestCase -from django.utils.encoding import force_str from .models import ( Foo, RenamedField, VerboseNameField, Whiz, WhizIter, WhizIterEmpty, @@ -56,8 +55,10 @@ class BasicFieldTests(TestCase): self.assertIsInstance(field.formfield(choices_form_class=klass), klass) def test_field_str(self): + f = models.Field() + self.assertEqual(str(f), '') f = Foo._meta.get_field('a') - self.assertEqual(force_str(f), 'model_fields.Foo.a') + self.assertEqual(str(f), 'model_fields.Foo.a') def test_field_ordering(self): """Fields are ordered based on their creation."""