On Mon, 2009-04-20 at 15:17 -0700, Paul McLanahan wrote: > I'm using a proxy model of django.contrib.auth.models.User to override > __unicode__ and add some extra methods. This also means that I use my > proxy model class in my ForeignKey and ManyToMany fields. This is all > find and good until I need to use request.user and assign it to an > instance of another of my models. Django tells me that I can't assign > an instance of User where I need an instance of my proxy class. Right > now I'm doing something I'm sure is very inefficient to get around > this: > > obj.author = ProxyUser.objects.get(pk=request.user.pk)
You could assign the ID directly rather than assigning the object
instance:
obj.author_id = request.user.id
But if you then try to use the obj.author object in your code, it will
still perform an extra DB lookup.
Another approach is to install a custom authentication backend that
returns instances of ProxyUser instead of User. This would ensure that
request.user is always an instance of your proxy class. I'm using a
backend like the following in a similar situation and it works great:
class ProxyUserBackend(ModelBackend):
def authenticate(self,username=None,password=None):
try:
user = ProxyUser.objects.get(username=username)
except ProxyUser.DoesNotExist:
user = None
if user is not None and user.check_password(password):
return user
return None
def get_user(self,user_id):
try:
return ProxyUser.objects.get(pk=user_id)
except ProxyUser.DoesNotExist:
return None
Cheers,
Ryan
--
Ryan Kelly
http://www.rfk.id.au | This message is digitally signed. Please visit
[email protected] | http://www.rfk.id.au/ramblings/gpg/ for details
signature.asc
Description: This is a digitally signed message part

