Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making first name, last name a required attribute rather than an optional one in Django's auth User model

I'm trying to make sure that the first name and last name field are not optional for the auth User model but I'm not sure how to change it. I can't use a sub class as I have to use the authentication system.

Two solutions I can think of are:

  1. to put the name in the user profile but it's a little silly to have a field that I can't use correctly.
  2. To validate in the form rather than in the model. I don't think this really fits with Django's philosophy...

For some reason I can't seem to find a way to do this online so any help is appreciated. I would have thought that this would be a popular question.

Cheers, Durand

like image 848
Durand Avatar asked Dec 11 '11 19:12

Durand


People also ask

Is username unique in Django user model?

The default User model in Django uses a username to uniquely identify a user during authentication. If you'd rather use an email address, you'll need to create a custom User model by either subclassing AbstractUser or AbstractBaseUser .

What is Auth_user_model?

AUTH_USER_MODEL is the recommended approach when referring to a user model in a models.py file. For this you need to create custom User Model by either subclassing AbstractUser or AbstractBaseUser.

What is username field in Django?

For Django's default user model, the user identifier is the username, for custom user models it is the field specified by USERNAME_FIELD (see Customizing Users and authentication). It also handles the default permissions model as defined for User and PermissionsMixin .


2 Answers

Simplest solution

  • Just create a custom UserRegisterForm which inherits the django's default UserCreationForm.
  • The first_name and last_name are already attributes of django's default User. If you want to make them as required fields, then recreate those fields as forms.CharField(...).

Now use your own User register form.

# Contents usersapp/forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm


# Inherit Django's default UserCreationForm
class UserRegisterForm(UserCreationForm):
    first_name = forms.CharField(max_length=50) # Required
    last_name = forms.CharField(max_length=50) # Required
    # All fields you re-define here will become required fields in the form

    class Meta:
        model = User
        fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2']
like image 69
Ali Sajjad Avatar answered Sep 20 '22 14:09

Ali Sajjad


I would definitely go with validating on the form. You could even go as far as having more form validation in the admin if you felt like it.

like image 33
Mbuso Avatar answered Sep 18 '22 14:09

Mbuso