Set optional fields from django.contrib.auth.User in Django

I'm trying to create a custom registration form in Django, my model looks like this:

#models.py

class UserRegister(models.Model):

   user = models.ForeignKey(User)

   GENDER_CHOICES = (
       ('M', 'Male'),
       ('F', 'Female'),
       ('O', 'Other'),
   )

   birthday = models.DateField(null = False, blank=False)

   gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=False)

      

I read about models.User and I saw that first_name and last_name are optional and email is not unique. I need first_name and last_name to be required attributes and email to be unique in my database, how can I do this?

Thank.

EDIT 1: If I inherit the model from the user, will my code be like this?

#models.py
class UserRegister(User):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField(unique=True)
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
        ('O', 'Other'),
    )
    birthday = models.DateField()
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

      

EDIT2: I solved my problem, what I did was copy AbstractUser

from django.contrib.auth.models

to mine models.py

and change the required fields. After that I edited mine settings.py

by adding AUTH_USER_MODEL = 'myApp.MyModelName' to it.

Here is the documentation: https://docs.djangoproject.com/en/dev/topics/auth/customizing/

+3


source to share


2 answers


Django model fields are by default equal NOT NULL

And if you want it to resolve values NULL

use the parameter null=True

.

If you want it to allow null value ('' but not null) then use the parameter blank=True

.

And if you want this field to be unique then set unique=True

class UserRegister(models.Model):

    first_name = models.CharField(max_length=150, null=True, blank=True)
    last_name = models.CharField(max_length=150, null=True, blank=True)
    email = models.EmailField(unique=True)

      




Maybe I misunderstood you, you want to change the fields of the user model.

And since you simply cannot update the user model declaration, if you want to do so, you have the following options:

  • Make other fields for storage, outside of the field user

    .
  • Inherits the model from user

    , does not use a combination, and then overrides the field.

Hope it helps.

+2


source


If you need to change what attributes are required, or if you need other user data, I would suggest writing your own user model rather than another model that references Django. The docs are here, it's not too hard: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model



+1


source







All Articles