Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin gives error "'Model' object has no attribute 'field_name'" after field name change

To improve my code and database, I needed to change the field name in a model away from a value that was confusing and close to a reserved word.

The original model was effectively this:

class Company(models.Model):
    my_old_name = models.CharField(max_length=100, db_index=True)

The new model is effectively this:

class Company(models.Model):
    my_new_name = models.CharField(max_length=100, db_index=True)

I ran:

python manage.py makemigrations my_app

and the migration code was this:

class Migration(migrations.Migration):

    dependencies = [
        ('my_app', '0004_auto_20160605_1852'),
    ]

    operations = [
        migrations.RenameField(
            model_name='company',
            old_name='my_old_name',
            new_name='my_new_name',
        ),
    ]

And then I executed:

python manage.py migrate

The site runs fine. All the pages show up and use 'new_name' as desired. However, I cannot use the admin site to administrate the database. It throw the error:

Error during template rendering

In template /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/s...  error at line 91

'Company' object has no attribute 'my_old_name'

I've been at this for a while with no luck. Any help would be appreciated.

As an addendum to the first suggestion, this is the contents of admin.py:

from django.contrib import admin
from .models import Company, Parameters

admin.site.register(Company)
admin.site.register(Parameters)

It doesn't contain 'my_old_name'...

like image 553
Photon Wrangler Avatar asked Jun 05 '16 22:06

Photon Wrangler


1 Answers

OK, found the error. The class model definition also contains the code:

def __str__(self):
    return self.my_old_name

Changing it to:

def __str__(self):
    return self.my_new_name

solved the problem. I missed this bit of code which tells admin what to display. (The model is more complex and contains another few dozen lines than snippets that I posted.)

like image 169
Photon Wrangler Avatar answered Oct 12 '22 11:10

Photon Wrangler