views:

417

answers:

1

We're running django alongside - and sharing a database with - an existing application. And we want to use an existing "user" table (not Django's own) to store user information.

It looks like it's possible to change the name of the table that Django uses, in the Meta class of the User definition.

But we'd prefer not to change the Django core itself.

So we were thinking that we could sub-class the core auth.User class like this :

class OurUser(User) :
    objects = UserManager()
    class Meta:
        db_table = u'our_user_table'

Here, the aim is not to add any extra fields to the customized User class. But just to use the alternative table.

However, this fails (likely because the ORM is assuming that the our_user_table should have a foreign key referring back to the original User table, which it doesn't).

So, is this sensible way to do what we want to do? Have I missed out on some easier way to map classes onto tables? Or, if not, can this be made to work?

Update :

I think I might be able to make the change I want just by "monkey-patching" the _meta of User in a local_settings.py

User._meta.db_table = 'our_user_table'

Can anyone think of anything bad that could happen if I do this? (Particularly in the context of a fairly typical Django / Pinax application?)

+6  A: 

You might find it useful to set up your old table as an alternative authentication source and sidestep all these issues.

Another option is to subclass the user and have the subclass point to your user-model. Override the save function to ensure that everything you need to do to preserve your old functionality is there.

I haven't done either of these myself but hopefully they are useful pointers.

Update What I mean by alternative authentication in this case is a small python script that says "Yes, this is a valid username / password" - It then creates an instance of model in the standard Django table, copies fields across from the legacy table and returns the new user to the caller.

If you need to keep the two tables in sync, you could decide to have your alternative authentication never create a standard django user and just say "Yes, this is a valid password and username"

Tom Leys
+1 Alternative authentication source.
Jarret Hardie
Setting up a backend which does what you need is the standard and recommended way to use other auth sources with Django, so that's what this person ought to do.Also, a quick Google search turns up quite a few auth backends in the wild that can be used as examples :)
James Bennett
Thanks. Maybe I wasn't clear enough but this is exactly what we are trying to do. (Ie. use alternative authentication and a subclass of User). The problem is that by making a sub-class, the ORM now expects the custom table (our legacy table) to have a field which is a foreign key to the original django auth_user table. And it throws an error because that doesn't exist.
interstar