Search code examples
pythondjangodjango-1.7

Django 1.7 app registry: defining blank/required based on DB query


I have a database field in which I want the required value to be dependent on some setting stored in the database. As a simple example:

class ModelSetting(models.Model):
    key=models.CharField(unique=True)
    value=models.BooleanField()

def get_setting(key):
    return ModelSetting.objects.get(key=key).value

class MyModel(models.Model):
    phone_number=models.CharField(required=get_setting("phone_required"))

The problem is that ModelSetting is defined in a completely different module from MyModel, so I guess at import time (when the phone_number field is evaluated) the ModelSetting model isn't available for use. Is this the case? And is there a possible workaround for it?

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

Solution

  • required isn't a valid option for models.CharField, you probably want to set blank instead.

    Are you sure that you want your models to depend on settings in the database? That means that Django will prompt to do migrations when the model settings change.

    Another approach would be to set blank=True in your model field, then check the phone_required setting in your forms. This way, you should be able to avoid AppRegistryNotReady errors.