Django 1.7 - Modifying a Model Property

Earlier in Django 1.6 and earlier, I used the following to make the User email attribute unique:

 class User(AbstractUser): USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] User._meta.get_field_by_name('email')[0]._unique=True 

I port to Django 1.7, but this code causes the following error:

 django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. 

traced all the way to User._meta.get_field_by_name('email')[0]._unique=True .

How do I port this to Django 1.7?

+1
source share
1 answer

According to the documentation, the ready() method of AppConfig is called when the registry is full, which means that models are also loaded, so references to models should not be a problem.

This line of code is still invalid because it is in ready() , though, as stated in the documentation:

You cannot import models into modules that define the application of configuration classes, but you can use get_model () to access the model class by name

Therefore, remove User._meta.get_field_by_name('email')[0]._unique=True from models.py and follow these steps in the application configuration:

 class AccountsConfig(AppConfig): name = 'modules.accounts' def ready(self): self.get_model('User')._meta.get_field_by_name('email')[0]._unique=True 
+5
source

All Articles