Opened 14 years ago

Closed 14 years ago

#16244 closed Uncategorized (invalid)

When calling contrib.admin.site.register, other apps' models.py should not be loaded

Reported by: jcspray Owned by: nobody
Component: contrib.admin Version: 1.3
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

In a scenario where I have multiple apps, depending on one another, I may from time to time want to have a unidirectional sharing of models between apps. For example, I might have an app for articles, and then an app for comments which imports the models from articles in order to associate comments with them.

If each app's models.py file includes an import of django.contrib.admin and a series of admin.site.register calls, then the above setup is not possible, due to a circular dependency. This arises because invoking the admin from one model appears to indirectly load the models.py modules from other apps as well. I can work around this by only calling into contrib.admin from an app whose models.py file is not reused by any other apps, but this is much more ugly than having each models.py file register its own models with the admin.

So what I have to do at the moment is this:

articles
  models.py
    defines Article
comments
  models.py
    imports articles.models.Article
    defines Comment
    registers Comment and Article with admin

But I should be able to do this:

articles
  models.py
    defines Article
    registers Article with admin
comments
  models.py
    imports articles.models.Article
    defines Comment
    registers Comment with admin

Change History (1)

comment:1 by Julien Phalip, 14 years ago

Resolution: invalid
Status: newclosed

The best practice to avoid those circular imports is to register your models for the admin inside separate admin.py files and then use admin.autodiscover() in your URLConf so that the the registration happens *after* all the models have been loaded. Please refer to the documentation [1] or ask for help on the django-users mailing list [2].

[1] https://docs.djangoproject.com/en/dev/ref/contrib/admin/

[2] http://groups.google.com/group/django-users/topics

Note: See TracTickets for help on using tickets.
Back to Top