Django: conflicting models in (third-party) application - django

I integrated a third party app into my Django project, and only when I import it will I get this error message.
RuntimeError: Conflicting 'task' models in application 'django_q': <class 'django_q.models.Task'> and <class 'models.Task'>.
I'm puzzled because my app runs well withouth it so I wonder how it could be an error on my side. I'm only using the app in its most simple use case. My general question is then: how can I investigate ?
So the app is django-q, a task queue (github). I installed it and called it in its most simple usage, following the good documentation.
CACHE = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'cache_table',
}
}
Q_CLUSTER = {
'name': 'DjangORM_queue',
'workers': 4,
'timeout': 3600,
'retry': 4000,
# 'queue_limit': 50,
# 'bulk': 10,
'orm': 'default'
}
api.py:
# api.py
# not putting all imports or __init__.py
def myhook(task):
print task.result
import ipdb; ipdb.set_trace()
def mymethod(request, pk, **kwargs):
from django_q.tasks import async, result
async('models.MyModel.method', pk, hook='myhook', sync=True)
Now manage.py runserver is ok, until I call my api and it reaches tasks.async. Full stacktrace:
Traceback (most recent call last):
File "/home/[...]/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/.../my-project/searchapp/models/api.py", line 965, in mymethod
tasks.async('models.MyModel.mymethod', pk, hook='myhook', sync=True)
File "/home/[...]/django_q/tasks.py", line 43, in async
return _sync(pack)
File "/home/[...]/django_q/tasks.py", line 176, in _sync
cluster.worker(task_queue, result_queue, Value('f', -1))
File "/home/[...]/django_q/cluster.py", line 369, in worker
m = importlib.import_module(module)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/[...]/django_q/models.py", line 15, in <module>
class Task(models.Model):
File "/home/[...]/django/db/models/base.py", line 309, in __new__
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
File "/home/[...]/django/apps/registry.py", line 221, in register_model
(model_name, app_label, app_models[model_name], model))
RuntimeError: Conflicting 'task' models in application 'django_q': <class 'django_q.models.Task'> and <class 'models.Task'>.
I first checked I don't have a model named Task, nor do my django installed apps. We don't.
I searched for a similar pb and found this SO answer, so I tried to tweak the imports of django-q, with no success (it doesn't mean I did it right though).
Is it a circular import (SO hint) ?
A Django bug report (which wasn't) is interesting also, I found comment 13 particarly (about double entries in sys.path and ways of import). My sys.path has [ my_project, …/site_packages/django_q, …/site_packages/] so I don't feel impacted by comment 13's description;
I couldn't reproduce the issue on a fresh django project;
I feel like trying another queuing system :/
Any hints on what could be wrong ?
Thanks !
ps: I could also point to my full repo

Too bad, I went with huey. It's simple and complete.
django-rq looks like a good solution too, with a django dashboard integration.

Related

Django runserver failing during admin site checks

When running runserver command, we are getting the error below which makes breaks the runserver command:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/checks.py", line 55, in check_admin_app
for site in all_sites:
File "/usr/local/lib/python3.7/_weakrefset.py", line 60, in __iter__
for itemref in self.data:
RuntimeError: Set changed size during iteration
This issue started to happen out of nowhere, since all the code related to AdminSite's wasn't modified in months. It's also not happening every time, but increasing in frequency of occurrence.
It doesn't seem to be related to the current implementation, since it's a django's runserver issue during the system checks, but here are the Implementation details:
class PaymentsAdminSite(AdminSite):
site_header = "Payments Admin Site"
site = PaymentsAdminSite(name="payments-admin")
#admin.register(models.Payment, site=site)
class PaymentsAdmin(admin.ModelAdmin):
def cancel(self, request, queryset):
pass
actions = (cancel,)
def get_queryset(self, request):
return models.Payment.objects.all()
# urls.py
url(r"^payments-admin/", site.urls)
Why is the error occurring:
When django runs it loads all of the apps and runs various checks. The default admin interface has various checks. The one that is failing is django.contrib.admin.checks.check_admin_app. It loops through all_sites and performs a check on each of these sites (AdminSites). The reason this error is being raised is that this set all_sites is being edited whilst it is being looped through (obviously a big no no).
How is it being edited? Well... all_sites refers to a WeakSet in admin.sites, and every time you instantiate an AdminSite, it adds itself to this WeakSet:
# django.contrib.admin.sites
all_sites = WeakSet()
class AdminSite:
def __init__(self, name='admin'):
...
all_sites.add(self)
Why is this happening?
I'm not 100% sure what is causing the inconsistency but I suspect the module is being loaded in a thread separate to the thread running the checks, and depending on which thread runs faster, the error occurs sometimes and not others.
How can I fix it?
Again, without a better idea of what is going on re. threads and what modules are getting imported when, I can't be 100% that this will fix the above, but I'll explain why I think it should work below. Put the following in your apps.py of the relevant app:
class PaymentsAdminSite(AdminSite):
site_header = "Payments Admin Site"
site = PaymentsAdminSite(name="payments-admin")
Why should it fix it
One of the first things Django does first is to register all of the apps in your INSTALLED_APPS. This involves importing all of the apps.py modules. After it has registered all of the apps, it will then register all of the models, and then it will call the ready method in each of the AppConfigs. It is the ready method in django.contrib.admin that is adding the check above, so hopefully by instantiating your SiteAdmin in an app.py file, it should be instantiated before the check is even added, let alone run.
Note you should only add the AdminSite to your apps.py, all of the registering of models to it, should stay in your admin.py since those models won't even be registered (to django) yet, at the point that apps.py is run.

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 use Flask-APScheduler in existed Flask app

I am trying to get familiar with Flask-APScheduler plug-in through the following sample code: https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/jobs.py#L1
My project has the following structure:
backend
run.py
application
__init__.py
utilities
__init__.py
views
models
where,
backend>run.py is:
from application import app
app.run(debug=True)
from application import scheduler
scheduler.start()
backend>application>__init__.py is:
from flask import Flask
app = Flask(__name__)
from application.utilities.views import Config
from flask_apscheduler import APScheduler
app.config.from_object(Config())
scheduler = APScheduler()
scheduler.init_app(app)
backend>application>utilities>__init__.py is empty
backend>application>utilities>models.py is empty
backend>application>utilities>views.py is:
class Config(object):
JOBS = [
{
'id': 'job1',
'func': 'application:utilities:views:job1',
'args': (1, 2),
'trigger': {
'type': 'cron',
'second': 10
}
}
]
def job1(a, b):
print(str(a) + ' ' + str(b))
However, I get the following error:
(env)$ python run.py local
Traceback (most recent call last):
File "run.py", line 1, in <module>
from application import app
File "HOME/backend/application/__init__.py", line 106, in <module>
scheduler.init_app(app)
File "/home/xxxxxx/.anaconda/envs/env/lib/python2.7/site-packages/flask_apscheduler/scheduler.py", line 73, in init_app
self.__load_jobs(app)
File "/home/xxxxxx/.anaconda/envs/env/lib/python2.7/site-packages/flask_apscheduler/scheduler.py", line 136, in __load_jobs
self.__load_job(job, app)
File "/home/xxxxxx/.anaconda/envs/env/lib/python2.7/site-packages/flask_apscheduler/scheduler.py", line 159, in __load_job
func = ref_to_obj(func)
File "/home/xxxxxx/.anaconda/envs/env/lib/python2.7/site-packages/apscheduler/util.py", line 264, in ref_to_obj
raise LookupError('Error resolving reference %s: error looking up object' % ref)
LookupError: Error resolving reference application:utilities:views:job1: error looking up object
Does my structure look like ok? Have a placed the right code in the right place? What should I change to make it work?
Your reference should only have one colon (":"). The colon separates the required import from the variable that has to be looked up. So:
'func': 'application.utilities.views:job1'

Haystack: KeyError in the elasticsearch_backend module

I'm using Django + Haystack + Elasticsearch.
When I send a request to this view
from haystack.views import FacetedSearchView
from .models import Object
class ObjectView(FacetedSearchView):
def extra_context(self):
extra = super(ObjectView, self).extra_context()
if not self.results:
extra['objects'] = Object.objects.all()
else:
searchqueryset = self.form.search()
results = [ result.pk for result in searchqueryset ]
extra['facets'] = self.results.facet_counts()
extra['objects'] = Object.objects.filter(pk__in=results)
extra['results'] = self.results
return extra
this error is raised:
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/views.py", line 49, in __call__
return self.create_response()
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/views.py", line 129, in create_response
(paginator, page) = self.build_page()
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/views.py", line 106, in build_page
self.results[start_offset:start_offset + self.results_per_page]
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/query.py", line 266, in __getitem__
self._fill_cache(start, bound)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/query.py", line 164, in _fill_cache
results = self.query.get_results(**kwargs)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/backends/__init__.py", line 485, in get_results
self.run(**kwargs)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 942, in run
results = self.backend.search(final_query, **search_kwargs)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/backends/__init__.py", line 26, in wrapper
return func(obj, query_string, *args, **kwargs)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 521, in search
distance_point=kwargs.get('distance_point'), geo_sort=geo_sort)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 571, in _process_results
raw_suggest = raw_results['suggest']['suggest']
KeyError: 'suggest'
A curious fact: the problem occurs only when the project is under production settings, even when I haven't changed a single thing involving Haystack or Elasticsearch in the settings_production module(except for the URL key).
project/settings_production.py
'URL': 'http://0.0.0.0:9200/'
In production, I'm using nothing more than a simple FastCGI.
And here's what really bothers me: sometimes I get no errors on this view, and everything works just fine...
Please, someone has an idea of what's going on?
Thanks a lot!
UPDATE:
SO, I setup my whole project in another computer. After some tests I verified:
this problem is not related to my production settings like I
described above;
the error is not raised when the elasticsearch service is stopped;
if the service is running:
when the method Object.objects.all() returns some QuerySet results, I got no errors;
when the method Object.objects.all() returns an empty QuerySet, the problem persists;
I guess this is some kind of bug in the Haystack's elasticsearch_backend module.
Still, i'm not sure.
Yup, it's a bug in haystack. I've put in a pull request, but in the meantime, options to get running are:
Set INCLUDE_SPELLING in your haystack settings to False, or
Use our fork: https://github.com/greenkahuna/django-haystack

Django unittests: The model is already registered Error

I come across several problems while trying django unittests library. Something strange happens:
I defined the test like this:
from django.core import management
from django.test import TestCase
from django.test.client import Client
from django.core import mail
from django.test.utils import setup_test_environment
from django.contrib.auth.models import User
from django.db import connection
from goserver.models import ActiveList
class GoserverTestCase(TestCase):
#fixtures = ['dat.json']
def setUp(self):
pass
def test_active_list_works(self):
c = Client()
response = c.post('/')
#print response.status_code
self.assertEquals(True, True)
But after the execution of the code it returns following error:
---------------------------------------------------------------------- Unit Test Code Coverage Results
---------------------------------------------------------------------- Traceback (most recent call last): File "manage.py", line 11, in <module>
execute_manager(settings) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/__init__.py", line 340, in execute_manager
utility.execute() File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/__init__.py", line 295, in execute
self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/base.py", line 192, in run_from_argv
self.execute(*args, **options.__dict__) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/base.py", line 219, in execute
output = self.handle(*args, **options) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/commands/test.py", line 33, in handle
failures = test_runner(test_labels, verbosity=verbosity, interactive=interactive) File "/opt/local/lib/python2.5/site-packages/django_test_coverage-0.1-py2.5.egg/django-test-coverage/runner.py", line 58, in run_tests
modules.extend(_package_modules(*pkg)) File "/opt/local/lib/python2.5/site-packages/django_test_coverage-0.1-py2.5.egg/django-test-coverage/runner.py", line 92, in _package_modules
modules.append(__import__(impstr + '.' + name, {}, {}, [''])) File "/Users/oleg/jin/goclub/trunk/jin/goserver/admin.py", line 11, in <module>
admin.site.register(ActiveList, ActiveListAdmin) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/contrib/admin/sites.py", line 64, in register
raise AlreadyRegistered('The model %s is already registered' % model.__name__) django.contrib.admin.sites.AlreadyRegistered: The model ActiveList is already registered silver:jin oleg$
Admin file looks like this:
from goserver.models import ActiveList, Game
from django.contrib import admin
class ActiveListAdmin(admin.ModelAdmin):
list_display = ('user', "is_Bot", "isActive")
admin.site.register(ActiveList, ActiveListAdmin)
admin.site.register(Game)
I run it all this way:
python manage.py test goserver
Also noticed that if I remove lines
c = Client()
response = c.post('/')
from a test case definition, then no error appears
Looking at the traceback, it looks like you have an app called django_test_coverage-0.1 which is importing your app's admin.py.
It is probably importing it from a different location, such as yourproject.yourapp.admin as opposed to yourapp.admin. Since it's technically seen as a different module, it is re-imported and the admin.site.register calls are made again. This causes the AlreadyRegistered error.
My suggestion would be to remove django_test_coverage app (or fix it).
My questions,
I don't see what is base type/class for TestCase - is it Django Test one, or from Unittest?
it is better to use from Django
How are you runnig test? using Django internal test command, by nose, by unittest? By Traceback I thing test command, but I am not quite sure.
What is you definitions for ActiveAdminList and ActiveList? Have you got maybe class Admin in Meta?
I solve this commenting the admin.autodiscover() line in the proye