django default auth system uses own auth models, but I have created my own model and i want, the auth process happens there

My model is :

class User(models.Model):
Nome = models.CharField(max_length=12)
Sobrenome = models.CharField(max_length=12)
Nickname = models.CharField(max_length=21,unique=True)
Email = models.CharField(max_length=40)
Password = models.CharField(max_length=20)
Created_Account_Date = models.DateTimeField(auto_now=False,auto_now_add=True)
Avatar = models.FileField(blank=True)
Number_Following = models.IntegerField(default=0,null=False)
Number_Followers = models.IntegerField(default=0,null=False)

def __str__(self):
    return "%s%s" %("@",self.Nickname)

I want use it to make auth process , and not django's default

1 Answers

robert lee On Best Solutions

You should definitely take a look at Customizing Authentication in the Django docs.

But I will try to break it down for you. You can follow along and add your specific fields:

First, to make a custom User model you need to inherit from AbstractUser or AbstractBaseUser. Keep in mind that the former provides more functionality than the latter and also requires less customization. So If you are not too familiar with Django's authentication system then I advise you inherit from AbstractUser to avoid unnecessary customization.


So let's say you want to extend the standard user model and add an EmailField. 'users' app
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)

Now we need to let Django know to use our brand new CustomUser model. so at our settings file we can go ahead and add:
AUTH_USER_MODEL = 'users.CustomUser'

You may want to have users provide an E-mail address when they register. For that you also need to customize your UserCreationForm so in our forms file:
from users.models import CustomUser
from django.contrib.auth.forms import UserCreationForm
class CustomUserCreationForm(UserCreationForm):
    email = forms.EmailField(max_length=200)

    class Meta:
        model = CustomUser
        fields = ('username', 'email', 'password1', 'password2')

Afterwards you need to go ahead and register your newly created CustomUser model in your

You will most likely need to make a custom UserChangeForm. And possibly a custom authentication backend(If you want users to login with e-mail for example.) But that probably deserves a new question by its own.

I strongly suggest you read the Django authentication docs(The link at the top). It will give you a better guidance to do the proper customization you for your specific needs.

Alternatively, If you feel this is too complicated at the moment you can also consider creating a separate model with the custom fields you need and then declaring a OneToOneField to link between the standard User model and your new model.

Best of luck!