python - Django 自定义管理 admin.site.register + admin.site.unregister 在第一个 HTTP GET 上与 AlreadyRegistered + NotRegistered 发生冲突(Apache + mod WSGI)

标签 python django apache mod-wsgi wsgi

在第一次 HTTP GET 期间(在守护进程模式下的 WSGI 重新加载之后),admin.site.unregister 抛出 NotRegistered 异常,但 admin.site.register 抛出 AlreadyRegistered 异常(catch-22?)但是,在随后的 HTTP GET,一切都加载得很好,没有错误。

设置:

  • Django 1.3
  • Apache 2.2
  • CentOS

设置.py:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    #'django.contrib.sites', #(this didn't seem to make a difference)
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    'django.contrib.admindocs',
    'base',
    'sample',
    'reports',
    'south',
)

模型.py:

from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin

class Company(models.Model):
  name = models.CharField(max_length=256)

class CompanyUser(models.Model):
  company = models.ForeignKey(Company)
  user = models.OneToOneField(User)

class CompanyUserInline(admin.StackedInline):
  model = CompanyUser
  max_num = 1
  can_delete = False

class CompanyUserAdmin(AuthUserAdmin):
  inlines = [ CompanyUserInline ]

# STUCK HERE !!
try:
  admin.site.unregister(User)
  # throws NotRegistered at / The model User is not registered
except:
  admin.site.register(User, CompanyUserAdmin)
  # throws AlreadyRegistered at / The model User is already registered

最佳答案

我在 freenode 的 #django 上找到了 mlavin 的答案

you are defining this in your models.py rather than admin.py (which is fine) but if you have any place in your code which does import * on that models file it will execute the register calls again

将 admin.py 中的内容移至 admin.py(从 models.py)解决了这个问题!不过,在我看来,我继承了代码库 - 我不确定为什么我要把这个代码片段放在 models.py 而不是 admin.py 中。

有趣的是:虽然这个问题从来没有通过“manage.py runserver”在本地出现过,但只有当我通过 Apache + WSGI 部署时,另一个人提到他们能够在本地重现它。奇怪。

但案件已结。

关于python - Django 自定义管理 admin.site.register + admin.site.unregister 在第一个 HTTP GET 上与 AlreadyRegistered + NotRegistered 发生冲突(Apache + mod WSGI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12412170/

相关文章:

apache - 使任何网络都无法访问测试服务器

c++ - [C/C++][CGIcc] GET 有效但 POST 导致错误消息

python - 具有多个参数的 app_template_filter

python - 使用 xlwings 和 python 复制工作表

python - 从 python 脚本调用 mongoimport

django - django.contrib.auth.User在Django源代码中定义在哪里

javascript - Django:当 JavaScript 代码使用 python 变量时,如何将 JavaScript 代码单独存放在静态文件夹中

apache - ReSTLet 用户认证

python - Scrapy 中项目的 has_key

python mahotas : Applying threshold filter and saving image as pgn