我有一个非常奇怪的问题。我编写了一个中间件,该中间件用自定义属性修补了请求对象。除了1个动作,它在整个项目中都能正常运行。他们是:
中间件:
class AssignSelectedProfileMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
headers = request.META
if not request.user.is_anonymous:
if headers.get(HEADER_PROFILE):
profile = Profile.objects.filter(pk=headers.get(HEADER_PROFILE),
archived=False,
user=request.user).first()
else:
profile = Profile.objects.filter(user=request.user).first()
if not profile:
raise MyProfileAuthorizationError("You are not allowed to use this profile.")
setattr(request, "user", request.user._wrapped)
setattr(request.user, "profile", profile)
response = self.get_response(request)
return response
操作:
@action(
methods=['get', 'patch'],
detail=False,
permission_classes=(IsAuthenticated,),
serializer_class=SafeProfileSerializer,
)
def me(self, request):
return Response(self.get_serializer(self.request.user.profile).data, status.HTTP_200_OK)
当我做出响应时-我发现请求在中间件中被成功修补,Profile对象存在,但是当我在视图中调试请求时-self.request.user.profile
抛出AttributeError: 'User' object has no attribute 'profile'
。注意-保存视图集中的另一个操作可以正常工作,并且user.profile
存在。为什么会发生这种情况?
编辑1:在中间件和操作中打印:
Middleware: {'_state': <django.db.models.base.ModelState object at 0x7f9e04b04908>, 'id': 1, 'password': 'pbkdf2_sha256$120000$Wxoqm8SATZWk$wVM5uRknaCig+nU7tlY4iQnkwgvJDavdHQHpKBRIstw=', 'last_login': datetime.datetime(2019, 5, 15, 9, 11, 36, 296195), 'is_superuser': False, 'username': 'username0', 'first_name': 'Benjamin', 'last_name': 'Allen', 'email': 'williamsdaniel@hotmail.com', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2019, 5, 15, 9, 11, 35, 808270), 'profile': <Profile: Benjamin Allen, administrator: False>}
View: {'_state': <django.db.models.base.ModelState object at 0x7f9e04b10358>, 'id': 1, 'password': 'pbkdf2_sha256$120000$Wxoqm8SATZWk$wVM5uRknaCig+nU7tlY4iQnkwgvJDavdHQHpKBRIstw=', 'last_login': datetime.datetime(2019, 5, 15, 9, 11, 36, 296195), 'is_superuser': False, 'username': 'username0', 'first_name': 'Benjamin', 'last_name': 'Allen', 'email': 'williamsdaniel@hotmail.com', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2019, 5, 15, 9, 11, 35, 808270)}
编辑2:
如果我在中间件中添加如下内容:
if request.path_info == '/api/users/me/':
setattr(request, "me_action_profile", profile)
并在这样的操作中调用它:
return Response(self.get_serializer(self.request.me_action_profile).data, status.HTTP_200_OK)
有效。但是为什么在这种特殊情况下我不能修补user
对象呢?