Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set optional username django User

I have to store Customer information in a Customer table. We don't need to store their username and password. But to create customer groups and users, I'm using django's User and Group Models. Here is the customer Model which I use to store it's basic information.

class Customer(models.Model):
    """
    The Customer 
    """
    UID = models.TextField(blank=True, null=True, db_index=True)
    fk_user = models.ForeignKey(User, primary_key=False)
    fk_details = models.ForeignKey(UserDetails, primary_key=False)
    fk_contact_details = models.ForeignKey(ContactDetails, primary_key=False)
    ...

This is a class method which creates user object for which later I'm using it to store customer information :

from django.contrib.auth.models import User
def create_user(self, req_dict):
    '''
    Create a new User 
    '''
    try:
        user=User.objects.create_user(**req_dict)
        user.save()
    except:
        return None
    return user

But this code is throwing an IntegrityError which is because we are not passing username in the req_dict

req_dict = {'first_name': u'John', 'last_name': u'Smith', 'email': u'[email protected]'}

What's the way to store username optional while creating a new user?

like image 560
trex Avatar asked Jan 08 '23 14:01

trex


1 Answers

If you want to use django.contrib.auth you can't make the username field optional. You always have to put a value in the database.

In order to bypass that, I suggest you generate a value in create_user() for username. You could either use a random value, or create a username from email. Just make sure that it's unique.

like image 193
zanderle Avatar answered Jan 15 '23 13:01

zanderle