Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
Meta Class in Models - Django
Next article icon

How to use User model in Django?

Last Updated : 22 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

The Django’s built-in authentication system is great. For the most part we can use it out-of-the-box, saving a lot of development and testing effort. It fits most of the use cases and is very safe. But sometimes we need to do some fine adjustment so to fit our Web application. Commonly we want to store a few more data related to our User but the next question might be that  how should a Django developer reference a User? The official Django docs list three separate ways:

  • User
  • AUTH_USER_MODEL
  • get_user_model()

Explanation:

Illustration of how to reference user model by an example. Consider a project  named mysite having an app name blog.

Refer to the following article to check how to create a project and an app in Django.  

How to Create Basic Project using MVT in Django ?     

How to Create an App in Django?

Method 1 – User model Directly : 

Inside the models.py add the following code:

Python3

from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    content= models.TextField()
    def __str__(self):
        return self.title
                      
                       

Register this model by adding the following code inside the admin.py.

from django.contrib import admin from .models import Post  # Register your models here. admin.site.register(Post)

Some kinds of projects may have authentication requirements for which Django’s built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username.

Django allows you to override the default user model by providing a value for the AUTH_USER_MODEL setting that references a custom model.

Method 2 – 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.

  • AbstractUser: Use this option if you are happy with the existing fields on the User model and just want to remove the username field.
  • AbstractBaseUser: Use this option if you want to start from scratch by creating your own, completely new User model.

Refer Below Article for Creating Custom User model:  

Creating Custom User Model

If you’ve already created a custom user model say CustomUser in an app called users , you’d reference it in your settings.py file as follows:

#settings.py  AUTH_USER_MODEL = 'users.CustomUser'

Then in blog models.py add the following code:

Python3

# blog/models.py
from django.conf import settings
from django.db import models
 
class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    content = models.TextField()
                      
                       

Register this model by adding the following code inside the admin.py.

from django.contrib import admin from .models import Post  # Register your models here. admin.site.register(Post)

Method 3 – get_user_model() :

If you reference User directly (for example, by referring to it in a foreign key), your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model.

The other way to reference the user model is via get_user_model which returns the currently active user model: either a custom user model specified in AUTH_USER_MODEL or else the default built-in User.

Inside the models.py add the following code:

Python3

from django.db import models
from django.contrib.auth import get_user_model
User=get_user_model()
# Create your models here.
class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    content= models.TextField()
    def __str__(self):
        return self.title
                      
                       

Register this model by adding the following code inside the admin.py.

from django.contrib import admin from .models import Post  # Register your models here. admin.site.register(Post)

Output – 

Creating instances with author as user



Next Article
Meta Class in Models - Django

M

muskan24r
Improve
Article Tags :
  • Python
  • Python Django
Practice Tags :
  • python

Similar Reads

  • Django Tutorial | Learn Django Framework
    Django, built with Python, is designed to help developers build secure, scalable, and feature-rich web applications quickly and efficiently. Whether you're a beginner looking to create your first dynamic website or an experienced developer aiming to enhance your skills, this tutorial will guide you
    11 min read
  • Django Basics

    • Django Basics
      Django is a Python-based web framework which allows us to quickly develop robust web application without much third party installations. It comes with many built-in features—like user authentication, an admin panel and form handling—that help you build complex sites without worrying about common web
      3 min read

    • Django Installation and Setup
      Installing and setting up Django is a straightforward process. Below are the step-by-step instructions to install Django and set up a new Django project on your system. Prerequisites: Before installing Django, make sure you have Python installed on your system. How to Install Django?To Install Djang
      2 min read

    • When to Use Django? Comparison with other Development Stacks
      Prerequisite - Django Introduction and Installation When to Use Django and Why? After getting to know the basics of Python, one should know when to use Django and why? Django is a high-level python based web framework which allows you to quickly create web applications without all of the installatio
      4 min read

    • Django Project MVT Structure
      Django is based on MVT (Model-View-Template) architecture. MVT is a software design pattern for developing a web application. MVT Structure has the following three parts - Model: The model is going to act as the interface of your data. It is responsible for maintaining data. It is the logical data s
      2 min read

    • How to Create a Basic Project using MVT in Django ?
      Prerequisite - Django Project MVT Structure Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server. Create a basic Project: To initi
      2 min read

    • How to Create an App in Django ?
      Prerequisite - How to Create a Basic Project using MVT in Django? Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. This article will take you through how to create a basic app and add functionalities
      4 min read

    • Django settings file - step by step Explanation
      Once we create the Django project, it comes with a predefined Directory structure having the following files with each file having its own uses. Let's take an example // Create a Django Project "mysite" django-admin startproject mysite cd /pathTo/mysite // Create a Django app "polls" inside project
      3 min read

    Django view

    • Views In Django | Python
      Django Views are one of the vital participants of the MVT Structure of Django. As per Django Documentation, A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, a redirect, a 404 error, an XML document, an ima
      6 min read

    • Django Function Based Views
      Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks. Django is based on MVT (Model View Template) architecture and revolves around CRUD (Create, Retrieve, Up
      7 min read

    • Django Class Based Views
      Django is a Python-based web framework that allows you to quickly create web applications. It has a built-in admin interface which makes it easy to work with it. It is often called a Class-Based included framework because it provides built-in facilities for every functionality. Class Based Generic V
      10 min read

    • Class Based vs Function Based Views - Which One is Better to Use in Django?
      Django...We all know the popularity of this python framework all over the world. This framework has made life easier for developers. It has become easier for developers to build a full-fledged web application in Django. If you're an experienced Django developer then surely you might have been aware
      7 min read

  • Django Templates
    Templates are the third and most important part of Django's MVT Structure. A template in Django is basically written in HTML, CSS, and Javascript in a .html file. Django framework efficiently handles and generates dynamic HTML web pages that are visible to the end-user. Django mainly functions with
    7 min read
  • Django Static File
    Static Files such as Images, CSS, or JS files are often loaded via a different app in production websites to avoid loading multiple stuff from the same server. This article revolves around, how you can set up the static app in Django and server Static Files from the same.Create and Activate the Virt
    3 min read
  • Django Model

    • Django Models
      A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating, or a
      10 min read

    • Django model data types and fields list
      The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean, save, or delete. Example: from django.db import models clas
      4 min read

    • Built-in Field Validations - Django Models
      Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. For example, IntegerField comes with built-in validation that it can only store integer values and that too in a p
      3 min read

    • How to use User model in Django?
      The Django’s built-in authentication system is great. For the most part we can use it out-of-the-box, saving a lot of development and testing effort. It fits most of the use cases and is very safe. But sometimes we need to do some fine adjustment so to fit our Web application. Commonly we want to st
      3 min read

    • Meta Class in Models - Django
      Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. D
      3 min read

    • get_object_or_404 method in Django Models
      Some functions are hard as well as boring to code each and every time. But Django users don't have to worry about that because Django has some awesome built-in functions to make our work easy and enjoyable. Let's discuss get_object_or_404() here. What is get_object_or_404 in Django?get_object_or_404
      2 min read

    Django Forms

    • Django Forms
      When one creates a Form class, the most important part is defining the fields of the form. Each field has custom validation logic, along with a few other hooks. This article revolves around various fields one can use in a form along with various features and techniques concerned with Django Forms. D
      6 min read

    • How to create a form using Django Forms ?
      Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. This post revolves around how to create a basic form using various Form Fields and attributes. Creating a form in Django is completely similar to creating a model
      3 min read

    • Django Form | Data Types and Fields
      When gathering user information to store in a database, we employ Django forms. Django offers a variety of model field forms for different uses, and these fields have a variety of patterns. The fact that Django forms can handle the fundamentals of form construction in just a few lines of code is the
      6 min read

    • Django Form | Build in Fields Argument
      We utilize Django Forms to collect user data to put in a database. For various purposes, Django provides a range of model field forms with various field patterns. The most important characteristic of Django forms is their ability to handle the foundations of form construction in only a few lines of
      3 min read

    • Python | Form validation using django
      Prerequisites: Django Installation | Introduction to DjangoDjango works on an MVT pattern. So there is a need to create data models (or tables). For every table, a model class is created. Suppose there is a form that takes Username, gender, and text as input from the user, the task is to validate th
      5 min read

    • Render Django Form Fields Manually
      Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). We have already covered on How to create and use a form in Django?. A form comes with 3 in-built methods that can be used to ren
      5 min read

    Django URLS

    • Django URL patterns | Python
      Prerequisites: Views in Django In Django, views are Python functions which take a URL request as parameter and return an HTTP response or throw an exception like 404. Each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration) Let t
      2 min read

    • Get parameters passed by urls in Django
      Django is a fully fleshed framework which can help you create web applications of any form. This article discusses how to get parameters passed by URLs in django views in order to handle the function for the same. You might have seen various blogs serving with urls like: - www.example.com/articles/9
      2 min read

    • url - Django Template Tag
      A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
      3 min read

    • URLField - Django Models
      URLField is a CharField, for a URL. It is generally used for storing webpage links or particularly called as URLs. It is validated by URLValidator. To store larger text TextField is used. The default form widget for this field is TextInput. Syntax field_name = models.URLField(max_length=200, **optio
      4 min read

    • URL fields in serializers - Django REST Framework
      In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_n
      5 min read

  • Python | Django Admin Interface
    In this article, we delve into the capabilities and advantages of the Django Admin Interface, exploring how its customizable features and streamlined workflows empower developers to effortlessly administer their projects, from data management to user interactions. Prerequisites: django-introduction-
    4 min read
  • More topics on Django

    • Handling Ajax request in Django
      Introduction This tutorial explains how to carry out an ajax request in the Django web framework. We will create a simple post-liking app as a part of the example. Glossary Project InitializationCreate modelsCreate viewsWrite URLsCarry out a request with Jquery Ajax.Register models to admin and add
      4 min read

    • Python | User groups with Custom permissions in Django
      Let's consider a trip booking service, how they work with different plans and packages. There is a list of product which subscriber gets on subscribing to different packages, provided by the company. Generally, the idea they follow is the level-wise distribution of different products. Let's see the
      4 min read

    • Python | Django Admin Interface
      In this article, we delve into the capabilities and advantages of the Django Admin Interface, exploring how its customizable features and streamlined workflows empower developers to effortlessly administer their projects, from data management to user interactions. Prerequisites: django-introduction-
      4 min read

    • Python | Extending and customizing django-allauth
      Prerequisite: Django-allauth setup and Configuration Let's deal with customizing django-allauth signup forms, and intervening in registration flow to add custom processes and validations. Extending the Signup Form or adding custom fields in Django-allauth: One of the most common queries about allaut
      4 min read

    • Django - Dealing with warnings
      Prerequisite : Django - Creating project Django is a great framework which provides you a lot of pre-defined services and workflow so that one can work flawlessly. Django apps are designed to make your code clean and reusable. Django works on the concept of DRY which means Don't Repeat Yourself. Aft
      2 min read

    • Python | Sessions framework using django
      The sessions framework can be used to provide persistent behavior for anonymous users on the website. Sessions are the mechanism used by Django for you to store and retrieve data on a per-site-visitor basis. Django uses a cookie containing a unique session ID. Django SessionsSo let's understand what
      4 min read

    • Django Sign Up and login with confirmation Email | Python
      Django by default provides an authentication system configuration. User objects are the core of the authentication system. Today we will implement Django's authentication system. Modules required: Django install, crispy_forms Django Sign Up and Login with Confirmation EmailTo install crispy_forms yo
      7 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences