Search code examples
djangodjango-modelsdjango-settings

Django: "AttributeError: type object 'AutoField' has no attribute 'rsplit'" after adding "DEFAULT_AUTO_FIELD" to settings.py


I just updated my Django project from 3.1.6 to 3.2.3. After running python manage.py runserver, the server ran with these warnings:

core.CoreUser: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
        HINT: Configure the DEFAULT_AUTO_FIELD setting or the CoreConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.

Then I remembered that I need to add a DEFAULT_AUTO_FIELD setting to settings.py after updating a project to Django from version < 3.2 to version >= 3.2, so I did:

# settings.py

DEFAULT_AUTO_FIELD = django.db.models.AutoField

Then I tried python manage.py runserver again, but this time I got a different warning:

(venv) C:\Users\Chris\my_project>python manage.py runserver
Traceback (most recent call last):
  ... (truncated for brevity)
  File "C:\Users\Chris\my_project\venv\lib\site-packages\django\utils\module_loading.py", line 13, in import_string
    module_path, class_name = dotted_path.rsplit('.', 1)
AttributeError: type object 'AutoField' has no attribute 'rsplit'

I thought that something about my migrations or database was causing the issue, so I deleted db.sqlite3 and all of the app's migrations. Then I ran a fresh python manage.py makemigrations, except that caused the same error: AttributeError: type object 'AutoField' has no attribute 'rsplit'

Any ideas why this might be happening?


Solution

  • It's because you need to wrap django.db.models.AutoField in quotes to make it a string, like this:

    # settings.py
    
    DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
    

    This kind of problem can be a little tricky to figure out, since Django doesn't give you any tips if you use a real import instead of a dotted module path as a string. Just be extra mindful that you are using strings in settings.py.