(편집 : 장고에 "Proxy Models"라는 완전히 다른 기능이 있다는 것을 알고 있습니다.이 기능은 도움이되지 않습니다. 필드를 UserProfile에 추가하십시오.)auth.user 모델 확장, 프록시 필드 및 장고 관리자
그래서 새로운 장고 앱을 시작하고 django.contrib.auth.models.User의 확장이며 다음과 같이 User에 대한 속성 요청을 실패한 UserProfile 모델을 만들고 있습니다. :
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
def __getattr__(self, name, *args):
if name == 'user' or name == '_user_cache':
raise AttributeError(name)
try:
return getattr(self.user, name, *args)
except AttributeError, e:
raise AttributeError(name)
이 일반적으로 잘 작동하지만 휴식은 내가 UserProfileAdmin.list_display에 User
필드를 사용하려고 할 때.
def validate(cls, model):
"""
Does basic ModelAdmin option validation. Calls custom validation
classmethod in the end if it is provided in cls. The signature of the
custom validation classmethod should be: def validate(cls, model).
"""
# Before we can introspect models, they need to be fully loaded so that
# inter-relations are set up correctly. We force that here.
models.get_apps()
opts = model._meta
validate_base(cls, model)
# list_display
if hasattr(cls, 'list_display'):
check_isseq(cls, 'list_display', cls.list_display)
for idx, field in enumerate(cls.list_display):
if not callable(field):
if not hasattr(cls, field):
if not hasattr(model, field):
try:
opts.get_field(field)
except models.FieldDoesNotExist:
raise ImproperlyConfigured("%s.list_display[%d], %r is not a callable or an attribute of %r or found in the model %r."
% (cls.__name__, idx, field, cls.__name__, model._meta.object_name))
문제는 그 USERPROFILE의 인스턴스가 프록시 필드가 반면, 예를 들어, 다음과 같습니다 문제는 여기에 관리자 유효성 검사 코드에 이메일을 보내면 UserProfile 클래스 자체는 그렇지 않습니다. 장고 쉘에서 시연 :
>>> hasattr(UserProfile, 'email')
False
>>> hasattr(UserProfile.objects.all()[0], 'email')
True
을 뒷조사 한 후, 내가 UserProfile._meta에 대한 django.db.models.options.Options.get_field를 오버라이드 (override) 할 것 같다. 하지만이 일을 해커가 아닌 방법으로 보이지 않습니다. (필자는 현재 매우 익숙한 해결책을 가지고 있습니다. 여기에는 원숭이 패치 UserProfile._meta가 포함됩니다. [get_field, get_field_by_name]) ... 제안 사항이 있습니까? 감사.
해킹 된 솔루션이 있음을 알리기 위해 업데이트되었습니다. 그러나 해키가 아닌 사람이 있으면 위대 할 것입니다. – rfrankel
아, 그건 그렇고, 우리에게'admin.py' 파일을 보여 주면 유용 할 수 있습니다. = P –