0
votes

Django auth has username and first_name fields. But username has field option unique=True. This prevents a user from giving first_name same as username when registering and raises IntegrityError. How to bypass this and also keeping username unique? ie. no two users should have the same username. But username can be same as first_name. And two users can have same first_name, last_name.

2
What will user authenticate with? May be example will help to understand your question.Rohan
User will authenticate with username and password. When registering, it should allow same value for username and first_name.Bharathwaaj
First name is valid for user name as long as it is site-wide unique. Doesn't make much sense to break username uniqueness for authentication.Pratik Mandrekar
If username is not unique, how can user authenticate?Rohan
Ok. My point is not that username uniqueness should be removed. But how to allow same value for username and first_name. Most of the sites allow this. For ex. In facebook, twitter etc. I could have my username same as first_name. I would like to have a similar functionality.Bharathwaaj

2 Answers

1
votes

You cannot achieve that. If you want to have the same value in fields first_name and username and one of them is not unique, the other one also cannot be unique.

As far as I understand what you're doing here, you just want to display first_name instead of username - to achieve that just use {{ user.first_name }} instead of just {{ user }}. If you need to store some additional information about users you can also define Profiles where you can implement your own __str__ method.

1
votes

You will have to implement custom authentication backend that used first_name as username.

During registration, you can duplicate username with first_name or generate random username which you will never use, as you will always use first_name instead.

You will have have to take care of

  • Take create while creating/registering user.
  • Username (in your case first name) should be unique

The code in authentication backend would be something like (this is just a sample code):

def authenticate(self, username=None, password=None):
    try:
        user = User.objects.get(first_name=username)
        if user.check_password(password):
            return user
    except User.DoesNotExist:
        return None 

Refer Writing authentication backend.

There are quite a few examples of how to user email to authenticate that you can refer to authenticate using first_name.