When I started working on my Django application, the first thing I wanted to do was to implement the Registration and Login functionality. In other words, what I wanted to implement was User Authentication.
In order to get the user registered, a form that lists all the fields that user needs to fill should be displayed and the Submit button should trigger an action of saving the details to the database i.e. in some model.
Here I am sharing what, at first, took long hours for me to realize. :p
It was when I had already started designing my own custom authentication system that I realized that Django comes with its own user authentication system and that the auth system has its own User Model.
Also, the fact that we can thereby extend the same with our custom fields.
Authentication support is bundled as a Django contrib module in django.contrib.auth. By default, the required configuration is already included in the settings.py generated by django-admin startproject, these consist of two items listed in your INSTALLED_APPS setting:
and two items in your MIDDLEWARE_CLASSES setting:
With these settings in place, running the command manage.py migrate creates the necessary database tables for auth related models and permissions for any models defined in your installed apps
The User Model
The default User Model has following primary attributes :
To use this, include the following line in the file :
from django.contrib.auth.models import User
One can have access to the attributes of User model with request.user object.
request.user is User model object.
It refers to the actual user model instance.
request.user.FIELDNAME will allow you to access all the fields of the user model.
For example, to display the details of the logged-in user, we can do the following:
You can also customize a ModelForm that makes use of the User model, for example, you may not want to include the email field in your form or other things. By customizing, what I mean is the way the fields look, what is included in the form, etc.
For details, you may have a look at the :
PS : Not forgetting to mention the name of the character – Ashutosh Singh who, during a casual conversation about Django, directed my attention towards the already existing user authentication system.