Django + heroku - import error on line that doesn't exist - django

I'm new to django (using python 2.7) and I was just trying to use heroku for the first time but I always get the following error:
remote: -----> Preparing static assets
remote: Collectstatic configuration error. To debug, run:
remote: $ heroku run python manage.py collectstatic --noinput
When I run that command, an import error regarding the django registration redux library shows up. I've had this problem before in Django and I fixed it by placing RequestSite under 'requests' and Site under 'models'. That solved the problem but the error still shows up in Heroku.
(venv) C:\Users\Carolina\Desktop\Coding\venv\project1>heroku run python manage.p
y collectstatic --noinput
Running python manage.py collectstatic --noinput on acla-acla... up, run.3645
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/_
_init__.py", line 350, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/_
_init__.py", line 324, in execute
django.setup()
File "/app/.heroku/python/lib/python2.7/site-packages/django/__init__.py", lin
e 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/app/.heroku/python/lib/python2.7/site-packages/django/apps/registry.py"
, line 115, in populate
app_config.ready()
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/app
s.py", line 22, in ready
self.module.autodiscover()
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/__i
nit__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/module_load
ing.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/app/.heroku/python/lib/python2.7/importlib/__init__.py", line 37, in im
port_module
__import__(name)
File "/app/.heroku/python/lib/python2.7/site-packages/registration/admin.py",
line 2, in <module>
from django.contrib.sites.models import RequestSite
ImportError: cannot import name RequestSite
The thing is - that line doesn't exist. I went to venv/lib/site-packages/registration/admin.py and line 2 is this one:
from django.contrib import admin
from django.contrib.sites.requests import RequestSite # HERE
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from registration.models import RegistrationProfile
from registration.users import UsernameField
class RegistrationAdmin(admin.ModelAdmin):
actions = ['activate_users', 'resend_activation_email']
list_display = ('user', 'activation_key_expired')
raw_id_fields = ['user']
search_fields = ('user__{0}'.format(UsernameField()), 'user__first_name', 'user__last_name')
def activate_users(self, request, queryset):
"""
Activates the selected users, if they are not already
activated.
"""
for profile in queryset:
RegistrationProfile.objects.activate_user(profile.activation_key)
activate_users.short_description = _("Activate users")
def resend_activation_email(self, request, queryset):
"""
Re-sends activation emails for the selected users.
Note that this will *only* send activation emails for users
who are eligible to activate; emails will not be sent to users
whose activation keys have expired or who have already
activated.
"""
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
for profile in queryset:
if not profile.activation_key_expired():
profile.send_activation_email(site)
resend_activation_email.short_description = _("Re-send activation emails")
admin.site.register(RegistrationProfile, RegistrationAdmin)
This is what I get with pip freeze, just in case:
Django==1.9
django-crispy-forms==1.5.2
django-registration==2.0.3
django-registration-redux==1.2
django-tinymce==2.2.0
Pillow==3.0.0
requests==2.9.0
South==1.0.2
stripe==1.27.1
wheel==0.24.0
Anyone knows why this is happening? Thanks in advance!
EDIT ----
Ok, so the problem was the one mentioned by Daniel Roseman. The library is broken in pypi and I had to tell heroku to install it from github (where the package is fixed).
So, I went to my requirements.txt file and replaced this line:
django-registration-redux==1.2
with this one:
-e git://github.com/macropin/django-registration.git#egg=django-registration==1.2
(I also removed 'django-registration==2.0.3' because it is an old version of django-registration-redux and was creating problems).
Hope this helps people with the same issue!

It sounds like you edited the code for your locally installed copy of django-registration-redux. But that won't have any effect on Heroku, since the library will be installed directly from PyPI, according to the version in your requirements.txt.
If the library is really broken, you will need to fork it and point your requirements.txt to your fixed version. However, looking at the code on GitHub, it doesn't actually seem to be broken; you just need to update the version you are pointing to.

Related

Flask Migrate "ValueError: Constraint must have a name"

I have created a flask migrate script ,however, when I running the upgrade function, I get the following error:
INFO [alembic.runtime.migration] Context impl SQLiteImpl.
INFO [alembic.runtime.migration] Will assume non-transactional DDL.
INFO [alembic.runtime.migration] Running upgrade -> 6378428b838a, empty message
Traceback (most recent call last):
File "migrate.py", line 22, in <module>
manager.run()
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/flask_script/__init__.py", line 417, in run
result = self.handle(argv[0], argv[1:])
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/flask_script/__init__.py", line 386, in handle
res = handle(*args, **config)
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/flask_script/commands.py", line 216, in __call__
return self.run(*args, **kwargs)
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/flask_migrate/__init__.py", line 95, in wrapped
f(*args, **kwargs)
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/flask_migrate/__init__.py", line 280, in upgrade
command.upgrade(config, revision, sql=sql, tag=tag)
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/alembic/command.py", line 298, in upgrade
script.run_env()
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/alembic/script/base.py", line 489, in run_env
util.load_python_file(self.dir, "env.py")
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/alembic/util/pyfiles.py", line 98, in load_python_file
module = load_module_py(module_id, path)
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/alembic/util/compat.py", line 173, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations/env.py", line 96, in <module>
run_migrations_online()
File "migrations/env.py", line 90, in run_migrations_online
context.run_migrations()
File "<string>", line 8, in run_migrations
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/alembic/runtime/environment.py", line 846, in run_migrations
self.get_context().run_migrations(**kw)
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/alembic/runtime/migration.py", line 518, in run_migrations
step.migration_fn(**kw)
File "/Users/slatifi/git/StaffTrainingLog/migrations/versions/6378428b838a_.py", line 23, in upgrade
batch_op.create_foreign_key(None, 'organisation', ['organisation'], ['id'])
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/contextlib.py", line 119, in __exit__
next(self.gen)
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/alembic/operations/base.py", line 325, in batch_alter_table
impl.flush()
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/alembic/operations/batch.py", line 106, in flush
fn(*arg, **kw)
File "/Users/slatifi/git/StaffTrainingLog/venv/lib/python3.7/site-packages/alembic/operations/batch.py", line 390, in add_constraint
raise ValueError("Constraint must have a name")
ValueError: Constraint must have a name
I have seen other people with the same error and they simply added render_as_batch to the env.py file. I did this but I still get the same error. Any thoughts?
Note: This is the modification I made in the env.py file:
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args,
render_as_batch=True
)
This is the upgrade script created by the migration
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2838e3e96536'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.add_column(sa.Column('organisation', sa.String(length=5), nullable=False))
batch_op.create_foreign_key(None, 'organisation', ['organisation'], ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='foreignkey')
batch_op.drop_column('organisation')
# ### en
d Alembic commands ###
This is normal because SQLite3 doesn't support ALTER tables.
You can pass the render_as_batch=True during the instantiation of Flask-Migrate like this :
migrate = Migrate(app,db,render_as_batch=True)
Don't need to modify the env file of Flask-Migrate.
In addition, to totally avoid the problem for your futures migrations, you can create a constraint naming templates for all types of constraints to the SQLAlchemy metadata, and then I think you will get consistent names.
See how to do this in the Flask-SQLAlchemy documentation. I'm copying the code example from the docs below for your convenience:
from sqlalchemy import MetaData
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
convention = {
"ix": 'ix_%(column_0_label)s',
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s"
}
metadata = MetaData(naming_convention=convention)
db = SQLAlchemy(app, metadata=metadata)
The other answers show how to configure Flask to use named constraints in the future, but that doesn't solve the problem of dropping existing unnamed constraints in Alembic migrations. To handle any existing unnamed constraints, you need to also define the naming convention in the migration script, as explained in the Alembic docs.
For example, suppose you're trying to do a migration that adds ON DELETE CASCADE to an existing foreign key in your test table. If you've followed one of the other answers (e.g. https://stackoverflow.com/a/62651160/470844) and added the naming_convention to the Flask init script, then flask db upgrade will generate something like this:
def upgrade():
with op.batch_alter_table('test', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='foreignkey')
batch_op.create_foreign_key(batch_op.f('fk_test_user_id_user'), 'user', ['user_id'], ['id'], ondelete='CASCADE')
Note that while the create_foreign_key call uses a constraint name (i.e. fk_test_user_id_user), the drop_constraint call still uses None as the constraint name, which will cause ValueError: Constraint must have a name error in this question's title.
To fix that, you need to edit the migration to use the naming_convention, and replace the None with the generated constraint name. For example, you'd change the above upgrade to:
naming_convention = {
"ix": 'ix_%(column_0_label)s',
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(column_0_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s"
}
def upgrade():
with op.batch_alter_table('test', schema=None, naming_convention=naming_convention) as batch_op:
batch_op.drop_constraint('fk_test_user_id_user', type_='foreignkey')
batch_op.create_foreign_key(batch_op.f('fk_test_user_id_user'), 'user', ['user_id'], ['id'], ondelete='CASCADE')
(In this example, you'd also need to disable SQLite foreign key support while running the migration script, e.g. using the technique here, to avoid the batch migration itself triggering a cacading delete. The problem is documented here.)
Installing Flask-Migrate helps to avoid code references to declarative_base or modifying the env.py file.
For apps with app factory, split the metadata assignment and the db initiation between the extensions.py and __init__.py files.
extensions.py:
from sqlalchemy import MetaData
from flask_sqlalchemy import SQLAlchemy
metadata = MetaData(
naming_convention={
"ix": 'ix_%(column_0_label)s',
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s"
}
)
db=SQLAlchemy(metadata=metadata)
__init__.py:
from flask import Flask, Blueprint
from config import ...
from flask_migrate import Migrate
from extensions import db
...
def create_app():
app = Flask(__name__,
template_folder='../app/templates')
app.config.from_object(config[...])
config[...].init_app(app)
db.init_app(app)
with app.app_context():
db.create_all()
migrate = Migrate(app, db)
...
from .templates.main import main
app.register_blueprint(main)
return app

How to fix "django ImproperlyConfigured exception: Requested setting, You must either define the environment variable DJANGO_SETTINGS_MODULE."

Our Django application uses Django Rest Framework, Oauth2 and double settings - one to develop and other to production, and a general one called base.py. The development.py is currently set up on manage.py file. We are also using django-cors-headers package.
This exception starts yesterday when I use ./manage.py runserver or another command. I tried to fix it. I read many posts from here (Stackoverflow) and in other websites, but I did not make it.
Could someone help me, please?
Traceback (most recent call last):
File "./manage.py", line 5, in <module>
from settings import base, development
File "/home/ijdev/Área de Trabalho/izio/izio-bank/settings/base.py", line 12, in <module>
from corsheaders.defaults import default_methods as cors_default_methods
File "/home/ijdev/Área de Trabalho/izio/Izioenv/lib/python3.7/site-packages/corsheaders/defaults.py", line 14, in <module>
CORS_ALLOW_HEADERS = getattr(settings, 'CORS_ALLOW_HEADERS', default_headers)
File "/home/ijdev/Área de Trabalho/izio/Izioenv/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__
self._setup(name)
File "/home/ijdev/Área de Trabalho/izio/Izioenv/lib/python3.7/site-packages/django/conf/__init__.py", line 64, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting CORS_ALLOW_HEADERS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
In your base settings you have
from corsheaders.defaults import default_methods as cors_default_methods
This causes a circular import because corsheaders tries to import settings.
To solve the problem, remove the import from settings.

How do you confirm django is using memcached?

I have a python django webserver that I am trying to use memcached to make it faster.
I have downloaded and installed memcached and started it a user called virtual as follows:
/usr/local/bin/memcached -u virtual &
on the django setting.py, I have put the memcached server as this:
MEMCACHE_HOSTS = ['192.168.101.1:11211']
I can do telnet 192.168.101.1 11211 and stats, I do see some statistics there etc.
How do I really know if my django server utilizing the memcached? Is there directory that I can look at or some files to confirm?
Thank you for any insight.
content of manage.py:
#!/usr/bin/env python
import os
import sys
from django.core.management import execute_from_command_line
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
from the command line:
phthon
from django.core.management import execute_from_command_line
and when I do this:
from django.core.cache import cache
I get these errors:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib64/python2.6/site-packages/django/core/cache/__init__.py", line 69, in <module>
if DEFAULT_CACHE_ALIAS not in settings.CACHES:
File "/usr/local/lib64/python2.6/site-packages/django/conf/__init__.py", line 54, in __getattr__
self._setup(name)
File "/usr/local/lib64/python2.6/site-packages/django/conf/__init__.py", line 47, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
You can test cache in Django's shell (python manage.py shell):
>>> from django.core.cache import cache
>>> cache.set('foo', 'bar', 600)
>>> cache.get('foo')
'bar'
If cache.get() returns the set value it means that cache is working as it should. Otherwise it will return None.
An other option is to start memcached with $ memcached -vv, since it will log all the cache accesses to the terminal. Or alternatively you can install monitoring tool for memcached (i.e. memcache-top) and check that something is happening in memcached while using your app.

Django custom management commands: AttributeError: 'module' object has no attribute 'Command'

I am trying to make a custom management command as show in the docs here: https://docs.djangoproject.com/en/dev/howto/custom-management-commands/
When I try to run the command from my project directory I am experiencing the following error:
AttributeError: 'module' object has no attribute 'Command'
Here is the file:
#event_expiration.py
from django.core.management.base import BaseCommand, CommandError
from app.models import Event
import datetime
class Command(BaseCommand):
help = 'deletes expired events'
def handle(self, *args, **options):
today = datetime.datetime.now()
events = Event.objects.filter(date=datetime.date(2011,11,11))
for e in events:
e.delete()
self.stdout.write('Expired events successfully deleted.')
The command I am running is :
$ python manage.py event_expiration
I've made sure I am adding the event_expiration.py file within management and commands folders and that those folders have init files. those are in one of my app folders.
Am I overlooking something here? Any help is appreciated, thanks!
EDIT:
Fellow SO user Yuji helped me attempt to debug this a bit but we are still stumped. heres what we did:
First, the full traceback and command:
(venv)matt#inspirion14z:~/Dropbox/PROD/ersvp.it$ python manage.py event_expiration
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 261, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 70, in load_command_class
return module.Command()
AttributeError: 'module' object has no attribute 'Command'
To see what was going on at django/core/management/init.py", line 70 I placed import pdb; pdb.set_trace() within the file.
While in debug mode we tried:
module.__file__
to check if the module was where expected, and it indeed was, with an output of:
'/home/matt/Dropbox/PROD/ersvp.it/app/management/commands/event_expiration.pyc'
Next, we tried manually importing Command in the shell:
>>> from app.management.commands.event_expiration import Command
Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: cannot import name Command
Still scratching my head!
I ran into the same issue and the problem was that my command class wasn't called exactly Command, as the docs says. Example:
class Command(NoArgsCommand):
# Do something here
What is your file structure like? It should be like so:
app/
__init__.py
management/
__init__.py
commands/
__init__.py
event_expiration.py
If the structure is as above, try the following:
python manage.py shell
>>> from app.management.commands import event_expiration
>>> dir(event_expiration)
['Account', 'BaseCommand', 'Callback', 'Command', 'CommandError', 'Comment', 'Status', 'User', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'clean_phone_number', 'csv', 'models', 'os', 're']
I've listed the pure output of running dir on a management command of my own. Give that a try, and report back what is available to the module. You might find yourself getting an error at this point, which may help diagnose. I'm suspecting a problem with importing django itself. I'm guessing the python manage.py shell will fail, which will mean it's not a problem with your command, but a problem with the project.
Edit 2:
The fact that check_expiration was visible in your dir output supports my theory that the folder structure is amiss in someway. Unless there's specifically a function named that within your module.
Please do the following and show the output:
cd /path/to/app/
find .
Also, show the entire contents of your event_expiration.py file, and the contents of your management/commands/__init__.py file. Be wary of spaces mixed with tabs as whitespace also.
Printing a queryset directly will also cause this error. For instance, I was trying to do something like this (just testing, not a real use case):
def handle(self, *args, **options):
ppl = People.objects.all()
print(ppl)
Resolution:
def handle(self, *args, **options):
ppl = People.objects.all()
print(str(ppl)) # Convert queryset to string
Conclusion: What works in shell doesn't necessarily work in a management command. Would be nice if someone can point out why.
I got this error by importing the regular click module instead of djclick
my_module/management/commands/run_thing.py
# import click # causes the error because not setup like djclick is
import djclick as click
#click.command()
#click.option("--thing", required=True, prompt=True)
def command(thing):
print(f"hi: {thing}"
Example run:
./manage.py run_thing --thing 123
...
hi: 123

My settings.py is called 4 times - any ideas why?

When I start the local dev server (./manage runserver) the settings.py is run four times. I noticed that, because a error/debug message is printed four times.
Any ideas how this can come? I don't even have an idea where to start looking. It's important for me because I'm struggling with the setup of Sentry, which doesn't report any errors of the site the way it is installed now.
Update:
I checked the imported module for import settings, there are none in my apps.
Then I added
import traceback; traceback.print_stack(); print
to settings.py. The result is:
File "./manage.py", line 5, in <module>
import settings # Assumed to be in the same directory.
File "(...)/myapp/settings.py", line 4, in <module>
import traceback; traceback.print_stack(); print
File "./manage.py", line 12, in <module>
execute_manager(settings)
(...)
File "(...)/site-packages/django/conf/__init__.py", line 73, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "(...)/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "(...)/myapp/../myapp/settings.py", line 4, in <module>
import traceback; traceback.print_stack(); print
File "./manage.py", line 5, in <module>
import settings # Assumed to be in the same directory.
File "(...)/myapp/settings.py", line 4, in <module>
import traceback; traceback.print_stack(); print
File "./manage.py", line 12, in <module>
execute_manager(settings)
(...)
File "(...)/site-packages/django/conf/__init__.py", line 73, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "(...)/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "(...)/myapp/../myapp/settings.py", line 4, in <module>
import traceback; traceback.print_stack(); print
Is that intended behaviour? If not, how can I find my error?
It's being accessed via different entries in sys.path. You should never attempt to import settings yourself; import django.conf.settings instead.
This behavior actually occurs in brand new Django 1.3 Projects. When the development server is started for the first time, it does four imports:
$ django-admin.py startproject test_project
$ cd test_project/
# settings.py
print "importing settings.py"
...
$ python manage.py runserver
importing settings.py
importing settings.py
importing settings.py
importing settings.py
Validating models...
0 errors found
Django version 1.3, using settings 'test_project.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
If you edit a file with the development server running, it only does two imports:
$ touch settings.py
Output:
importing settings.py
importing settings.py
Validating models...
0 errors found
Django version 1.3, using settings 'test_project.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
I'm not sure why it does this, or if it does it on non-development servers. But the behavior does appear to be normal.
If you track imports in settings.py, it doesn't persist values across the multiple imports:
# settings.py
import_count = 0
import_count += 1
print "import count: %d" % import_count
Fresh start:
$ python manage.py runserver
import count: 1
import count: 1
import count: 1
import count: 1
Validating models...
Changed a file:
import count: 1
import count: 1
Validating models...
So maybe it's just reading the file to configure itself, and verify that everything is OK, before importing it for the final time and actually using it?