Django runserver failing during admin site checks - django

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.

Related

Is there a workaround for Django's `ModelDoesNotExist` error in a situation like this?

So I get a ModelDoesNotExist error when I run manage.py runserver because in a file in my directory, I make a query to a table which has not been populated yet.
def __init__(self):
self.spotify_object = SocialToken.objects.get(account__provider="spotify")
The above is a class instantiated to perform some sort of authentication and the SocialToken table gets populated only after I login. Now, I was wondering if there was a way to escape the error by triggering this part of the code only after I login? I only use the class in an endpoint, and during that period, the table would have been populated but the fact that it is not populated before running the server is causing a DoesNotExist error. Is there a solution to this?
Traceback
File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\Sparison\views.py", line 4, in <module>
from .authentication import SparisonCacheHandler
File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\Sparison\authentication.py", line 43, in
<module>
cache_handler = SparisonCacheHandler() ,
File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\Sparison\authentication.py", line 25,
in __init__
self.spotify_object = SocialToken.objects.get(account__provider="spotify")
File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\venv\lib\site-
packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\venv\lib\site-
packages\django\db\models\query.py", line 429, in get
raise self.model.DoesNotExist(
allauth.socialaccount.models.DoesNotExist: SocialToken matching query does not exist.
In my views.py, I import the class which has the query and the error comes up.
There are two ways to avoid the DoesNotExist Error.
A) Use .filter() instead of .get()
Filtering leads to an empty queryset when the search comes up empty.
def __init__(self):
self.spotify_object = SocialToken.objects.filter(account__provider="spotify")
B) Use get_object_or_404() instead of .get()
This is a built-in function by django:
Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.
Django Documentation
def __init__(self):
self.spotify_object = SocialToken.objects.get_object_or_404(account__provider="spotify")
Hope I could help you. Have a nice day.

Django: conflicting models in (third-party) application

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.

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

Django syncdb exception after updating to 1.4

So I was developing an app in Django and needed a function from the 1.4 version so I decided to update.
But then a weird error appeared when I wanted to do syncdb
I am using the new manage.py and as You can see it makes some of the tables but then fails :
./manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
Traceback (most recent call last):
File "./manage.py", line 9, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/core/management/base.py", line 371, in handle
return self.handle_noargs(**options)
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/core/management/commands/syncdb.py", line 91, in handle_noargs
sql, references = connection.creation.sql_create_model(model, self.style, seen_models)
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/db/backends/creation.py", line 44, in sql_create_model
col_type = f.db_type(connection=self.connection)
TypeError: db_type() got an unexpected keyword argument 'connection'
I had the same issue, the definition for my custom field was missing the connection parameter.
from django.db import models
class BigIntegerField(models.IntegerField):
def db_type(self, connection):
return "bigint"
Although already old, answered and accepted question but I am adding my understanding I have added it because I am not using customized type and it is a Django Evolution error (but not syncdb)evolve --hint --execute. I think it may be helpful for someone in future. .
I am average in Python and new to Django. I also encounter same issue when I added some new features to my existing project. To add new feature I had to add some new fields of models.CharField() type,as follows.
included_domains = models.CharField(
"set of comma(,) seprated list of domains in target emails",
default="",
max_length=it_len.EMAIL_LEN*5)
excluded_domains = models.CharField(
"set of comma(,) seprated list of domains NOT in target emails",
default="",
max_length=it_len.EMAIL_LEN*5)
The Django version I am using is 1.3.1:
$ python -c "import django; print django.get_version()"
1.3.1 <--------# version
$python manage.py syncdb
Project signature has changed - an evolution is required
Django Evolution: Django Evolution is an extension to Django that allows you to track changes in your models over time, and to update the database to reflect those changes.
$ python manage.py evolve --hint
#----- Evolution for messagingframework
from django_evolution.mutations import AddField
from django.db import models
MUTATIONS = [
AddField('MessageConfiguration', 'excluded_domains', models.CharField, initial=u'', max_length=300),
AddField('MessageConfiguration', 'included_domains', models.CharField, initial=u'', max_length=300)
]
#----------------------
Trial evolution successful.
Run './manage.py evolve --hint --execute' to apply evolution.
The trial was susses and when I tried to apply changes in DB
$ python manage.py evolve --hint --execute
Traceback (most recent call last):
File "manage.py", line 25, in <module>
execute_manager(settings)
File "/var/www/sites/www.taxspanner.com/django/core/management/__init__.py", line 362, in execute_manager
utility.execute()
File "/var/www/sites/www.taxspanner.com/django/core/management/__init__.py", line 303, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/var/www/sites/www.taxspanner.com/django/core/management/base.py", line 195, in run_from_argv
self.execute(*args, **options.__dict__)
File "/var/www/sites/www.taxspanner.com/django/core/management/base.py", line 222, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django_evolution-0.6.9.dev_r225-py2.7.egg/django_evolution/management/commands/evolve.py", line 60, in handle
self.evolve(*app_labels, **options)
File "/usr/local/lib/python2.7/dist-packages/django_evolution-0.6.9.dev_r225-py2.7.egg/django_evolution/management/commands/evolve.py", line 140, in evolve
database))
File "/usr/local/lib/python2.7/dist-packages/django_evolution-0.6.9.dev_r225-py2.7.egg/django_evolution/mutations.py", line 426, in mutate
return self.add_column(app_label, proj_sig, database)
File "/usr/local/lib/python2.7/dist-packages/django_evolution-0.6.9.dev_r225-py2.7.egg/django_evolution/mutations.py", line 438, in add_column
sql_statements = evolver.add_column(model, field, self.initial)
File "/usr/local/lib/python2.7/dist-packages/django_evolution-0.6.9.dev_r225-py2.7.egg/django_evolution/db/common.py", line 142, in add_column
f.db_type(connection=self.connection), # <=== here f is field class object
TypeError: db_type() got an unexpected keyword argument 'connection'
To understand this exception I check that this exception is something similar to:
>>> def f(a):
... print a
...
>>> f('b', b='a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got an unexpected keyword argument 'b'
>>>
So the function signature has been changed.
Because I have not added any new customized or enum fields but only two similar fields that was already in model and char type field is supported by most of database (I am ussing PostgreSQL) even I was getting this error!
Then I read from #: Russell Keith-Magee-4 Reply.
What you've hit here is the end of the deprecation cycle for code that
doesn't support multiple databases.
In Django 1.2, we introduced multiple database support; in order to
support this, the prototype for get_db_preb_lookup() and
get_db_prep_value() was changed.
For backwards compatibility, we added a shim that would transparently
'fix' these methods if they hadn't already been fixed by the
developer.
In Django 1.2, the usage of these shims raised a
PendingDeprecationWarning. In Django 1.3, they raised a
DeprecationWarning.
Under Django 1.4, the shim code was been removed -- so any code that
wasn't updated will now raise errors like the one you describe.
But I am not getting any DeprecationWarning warning assuming because of newer version of Django Evolution.
But from above quote I could understand that to support multiple databases function signature is added and an extra argument connection is needed. I also check the db_type() signature in my installation of Django as follows:
/django$ grep --exclude-dir=".svn" -n 'def db_type(' * -R
contrib/localflavor/us/models.py:8: def db_type(self):
contrib/localflavor/us/models.py:24: def db_type(self):
:
:
Ialso refer of Django documentation
Field.db_type(self, connection):
Returns the database column data type for the Field, taking into account the connection
object, and the settings associated with it.
And Then I could understand that to resolve this issue I have to inherited models.filed class and overwrite def db_type() function. And because I am using PostgreSQL in which to create 300 chars type field I need to return 'char(300)'. In my models.py I added:
class CharMaxlengthN(models.Field):
def db_type(self, connection):
return 'char(%d)' % self.max_length # because I am using postgresql
If you encounter similar problem please check your underline DB's manual that which type of column you need to create and return a string.
And changed the definition of new fields (that I need to add) read comments:
included_domains = CharMaxlengthN( # <--Notice change
"set of comma(,) seprated list of domains in target emails",
default="",
max_length=it_len.EMAIL_LEN*5)
excluded_domains = CharMaxlengthN( # <-- Notice change
"set of comma(,) seprated list of domains NOT in target emails",
default="",
max_length=it_len.EMAIL_LEN*5)
Then I executed same command that was failing previously:
t$ python manage.py evolve --hint --execute
You have requested a database evolution. This will alter tables
and data currently in the None database, and may result in
IRREVERSABLE DATA LOSS. Evolutions should be *thoroughly* reviewed
prior to execution.
Are you sure you want to execute the evolutions?
Type 'yes' to continue, or 'no' to cancel: yes
Evolution successful.
I also check my DB and tested my new added features It is now working perfectly, and no DB problem.
If you wants to create ENUM field read Specifying a mySQL ENUM in a Django model.
Edit: I realized instead of sub classing models.Field I should have inherit more specific subclass that is models.CharField.
Similarly I need to create Decimal DB fields so I added following class in model:
class DecimalField(models.DecimalField):
def db_type(self, connection):
d = {
'max_digits': self.max_digits,
'decimal_places': self.decimal_places,
}
return 'numeric(%(max_digits)s, %(decimal_places)s)' % d

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