Allow duplicate usernames

I'm working on a project in django which calls for having separate groups of users in their own username namespace.

So for example, I might have multiple "organizations", and username should only have to be unique within that organization.

I know I can do this by using another model that contains a username/organization id, but that still leaves this useless (and required) field on the defualt django auth User that I would have to populate with something.

I've already written by own auth backend that authenticates a user against LDAP. However, as I mentioned before, I am still stuck with the problem of how to populate / ignore the username field on the default django user.

Is there a way to drop the uniqueness constraint for the username for Django auth users?


I'm not sure if this is exactly what you're looking for, but I think you could use a hack similar to what is in this answer.

The following code works, as long as it is in a place that gets executed when Django loads your models.

from django.contrib.auth.models import User

User._meta.get_field('username')._unique = False

Note that this won't change the database unique constraint on the auth_user table if it has been already been created. Therefore you need to make this change before you run syncdb. Alternatively, if you don't want to recreate your auth_user table, you could make this change and then manually alter the database table to remove the constraint.


What you can do is extend the User model. For the User table, generate a username (eg A_123, A_345) that will not be displayed at all in the site.

Then create a new model that extends User.

class AppUser(User):
    username = models.CharField...
    organization = models.CharField...

You then create a custom authentication backend that use AppUser instead of the User object.


I have not personally been required to find a solution to this, but one way to tackle this (from an SAAS perspective) would be to prefix the username with an organizational identifier (presuming unique organizations). For example: subdomain.yoursite.com would equate to a user with the username: subdomain_username. You would just have to code some business logic on login to a subdomain to tack that onto the username.

链接地址: http://www.djcxy.com/p/5768.html

上一篇: django:是否有可能将用户从另一个域注册到子域中?

下一篇: 允许重复的用户名