问题
class MyUser(User):
class Meta:
proxy = True
def do_something:
...
With the above, I extend the behavior of the Django User Model using the proxy model technique. I was hoping that I could somehow customize request.user, so that MyUser instance, instead of User instance, is assigned to it every time. How could I implement that, if possible?
回答1:
You can inherit a new middleware class from AuthMiddleware or create a separate middleware which will process request after django's auth and change request.user to your user instance.
回答2:
I looked at code and my idea is here. Late but I think can be useful for others
In file myapp/backends.py
from django.contrib.auth import backends
from models import ProxyUser
class ModelBackend(backends.ModelBackend):
'''
Extending to provide a proxy for user
'''
def get_user(self, user_id):
try:
user = ProxyUser.objects.get(pk=user_id)
except ProxyUser.DoesNotExist:
return None
return user if self.user_can_authenticate(user) else None
And on settings.py
AUTHENTICATION_BACKENDS = (
'myapp.backends.ModelBackend',
)
来源:https://stackoverflow.com/questions/9593877/customizing-request-user-with-a-proxy-model-that-extends-django-user-model