SlideShare a Scribd company logo
Two Scoops of Django
Chapter 16 - Dealing with the User Model

Alfred
When you check out
your user model…
or…
How it authenticates…
login

Authentication
Backends

authenticate

Model.User
Model.UserManager

pass

User
View

you know, the best way is to trace the python	

source code.	

backends: contrib.auth.backends.py	

model: contrib.auth.models.py	

admin(user view): contrib.auth.admin.py

•
•
•
Basic
From Django 1.5 onwards, the official preferred way to attach ForeignKey, OneToOneField, 	

or ManyToManyField to User is as follows:	


from django.conf import settings	
from django.db import models	

!
class IceCreamStore(models.model):	
owner = models.OneToOneField(settings.AUTH_USER_MODEL)	
title = models.CharField(max_length=255)
To customize your user
table, there are 3
options...
Warranty
We suggest that you carefully try out option #1
below, as it should work with a minimum of effort.
For Django 1.5-style custom User model definitions,
we recommend option #2 and option #3 for new
projects only.	

!

This is is because custom User model definitions for
option #2 and option #3 adds new User tables to
the database that will not have the existing project
data. Unless project-specific steps are taken to
address matters, migration means ORM connections
to related objects will be lost.
Option 1 - Link back
You continue to use User (called preferably via
django.contrib.auth.get user model()) and keep your related
fields in a separate model (e.g. Profile).	

from django.conf import settings	
from django.db import models	
class UserProfile(models.Model):	
# If you do this you need to either have a post_save signal or	
#

redirect to a profile_edit view on initial login.	

user = models.OneToOneField(settings.AUTH_USER_MODEL)	
favorite_ice_cream = models.CharField(max_length=30)
Option 2 AbstractUser
Choose this option if you like Django’s User model fields the
way they are, but need extra fields	

!from

django.contrib.auth.models import AbstractUser	

from django.db import models	
from django.utils.translation import ugettext_lazy as _	

!
class KarmaUser(AbstractUser):	
karma = models.PositiveIntegerField(_("karma"),	
default=0,	
blank=True)	
#Setting.py	
AUTH_USER_MODEL = "profile.KarmaUser"
Option 3 - Subclass
AbstractBaseUser
	


AbstractBaseUser is the bare-bones option with only 3 fields:
password, last login, and is active.	

!

	

 Let’s try it out with a custom User model for the Two
Scoops project. Here are our requirements: 	

We need an email address. 	

We need to handle permissions per the traditional
django.contrib.auth.models use of PermissionsMixin;
providing standard behavior for the Django admin. 	

We don’t need the first or last name of a user. 	

We need to know their favorite ice cream topping. 	


•
•
•
•
Option 3 - cont.(1)

	


1. Start from model.	

2. Model.UserManager create User -> override it to create
TwoScoopsUser	

3. We need TwoScoopsUser!
class TwoScoopsUser(AbstractBaseUser, PermissionsMixin):	
email = models.EmailField(	
verbose_name='email address',	
max_length=255,	
unique=True,	
db_index=True,	
)	
favorite_topping = models.CharField(max_length=255)	
is_active = models.BooleanField(default=True)	
is_admin = models.BooleanField(default=False)	
is_staff = models.BooleanField(default=False)	

!
!

objects = TwoScoopsUserManager()	
USERNAME_FIELD = 'email'	
REQUIRED_FIELDS = ['favorite_topping']
Option 3 - cont.(2)
Implement usage functions…
def get_full_name(self): return self.email	

!
def get_short_name(self): return self.email	

!
def __unicode__(self): return self.email	

!
def has_perm(self, perm, obj=None): return True	

!
def has_module_perms(self, app_label): return True
Option 3 - cont. (3)

	


Let’s write Model.UserManager to create TwoScoopsUser
class TwoScoopsUserManager(BaseUserManager):	
def create_user(self, email, favorite_topping, password=None):	
"""	
Creates and saves a User with the given email, date of	
birth and password.	
"""	
##Skip…	
user = self.model(	
email=TwoScoopsUserManager.normalize_email(email),	
favorite_topping=favorite_topping,	
)	

!
user.set_password(password)	
user.save(using=self._db)	
return user
Option 3 - cont. (4)

	


Let’s write Model.UserManager to create TwoScoopsUser
!
def create_superuser(self, email, favorite_topping, password):	
"""	
Creates and saves a superuser with the given email, date of	
birth and password.	
"""	
user = self.create_user(email,	
password=password,	
favorite_topping=favorite_topping	
)	
user.is_admin = True	
user.is_staff = True	
user.is_superuser = True	
user.save(using=self._db)	
return user
Option 3 - Let Admin
show your data.
	


Basically, override contrib.auth.admin …
class TwoScoopsUserAdmin(UserAdmin):	
# The forms to add and change user instances	
form = TwoScoopsUserChangeForm	
add_form = TwoScoopsUserCreationForm	

!

!

# The fields to be used in displaying the User model.	
# These override the definitions on the base UserAdmin	
# that reference specific fields on auth.User.	
list_display = ("email", "is_staff", "favorite_topping")	
list_filter = ("is_staff", "is_superuser", "is_active", "groups")	
search_fields = ("email", "favorite_topping")	
ordering = ("email",)	
filter_horizontal = ("groups", "user_permissions",)	
fieldsets = (	
(None, {"fields": ("email", "password")}),	
("Personal info", {"fields": ("favorite_topping",)}),	
("Permissions", {"fields": ("is_active", "is_staff", "is_superuser", "groups", "user_permissions")}),	
("Important dates", {"fields": ("last_login",)}),	
)	
add_fieldsets = ((None, {	
"classes": ("wide",),	
"fields": ("email", "favorite_topping", "password1", "password2")}), )
Option 3 - Let Admin
show your data. (2)
	


Implement your forms
class TwoScoopsUserCreationForm(UserCreationForm):	
"""A form for creating new users. Includes all the required	
fields, plus a repeated password."""	
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)	
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)	
#favorite_topping = forms.CharField( label='Faborate topping', widget=forms.TextInput)	

!

class Meta:	
model = TwoScoopsUser	
fields = ('email', 'favorite_topping')	
	
class TwoScoopsUserChangeForm(UserChangeForm):	
"""A form for updating users. Includes all the fields on	
the user, but replaces the password field with admin's	
password hash display field.	
"""	
password = ReadOnlyPasswordHashField()	

!

class Meta:	
model = TwoScoopsUser	
fields = ["email", "password", "favorite_topping", "is_active",	
"is_staff", "is_superuser", "groups", "user_permissions",	
"last_login"]
Two scoopsofdjango ch16   dealing with the user model
Thanks
Ad

More Related Content

What's hot (20)

Forms, Getting Your Money's Worth
Forms, Getting Your Money's WorthForms, Getting Your Money's Worth
Forms, Getting Your Money's Worth
Alex Gaynor
 
Common Pitfalls Experienced in Java
Common Pitfalls Experienced in JavaCommon Pitfalls Experienced in Java
Common Pitfalls Experienced in Java
Exist
 
Validation
ValidationValidation
Validation
suresh pasupuleti
 
Jsf lab
Jsf labJsf lab
Jsf lab
Yu-Ting Chen
 
Html basics 11 form validation
Html basics 11 form validationHtml basics 11 form validation
Html basics 11 form validation
H K
 
Presentation technico-commercial-ruby-on-rails
Presentation technico-commercial-ruby-on-railsPresentation technico-commercial-ruby-on-rails
Presentation technico-commercial-ruby-on-rails
Novelys
 
Xml operations in odoo
Xml operations in odooXml operations in odoo
Xml operations in odoo
Celine George
 
What's New in newforms-admin
What's New in newforms-adminWhat's New in newforms-admin
What's New in newforms-admin
brosner
 
Working With The Symfony Admin Generator
Working With The Symfony Admin GeneratorWorking With The Symfony Admin Generator
Working With The Symfony Admin Generator
John Cleveley
 
The Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contribThe Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contrib
Tzu-ping Chung
 
Documentation For Tab Setup
Documentation For Tab SetupDocumentation For Tab Setup
Documentation For Tab Setup
vkeeton
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
Knoldus Inc.
 
HTML Form Part 1
HTML Form Part 1HTML Form Part 1
HTML Form Part 1
Teresa Pelkie
 
Specs2
Specs2Specs2
Specs2
Piyush Mishra
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
Mohamed Mosaad
 
Repensando o Desenvolvimento Web com Ruby on Rails
Repensando o Desenvolvimento Web com Ruby on RailsRepensando o Desenvolvimento Web com Ruby on Rails
Repensando o Desenvolvimento Web com Ruby on Rails
Dante Regis
 
Django Admin (Python meeutp)
Django Admin (Python meeutp)Django Admin (Python meeutp)
Django Admin (Python meeutp)
Ines Jelovac
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
Mohit Jain
 
Django Bogotá. CBV
Django Bogotá. CBVDjango Bogotá. CBV
Django Bogotá. CBV
ctrl-alt-delete
 
ALPHA Script - XML Model
ALPHA Script - XML ModelALPHA Script - XML Model
ALPHA Script - XML Model
PROBOTEK
 
Forms, Getting Your Money's Worth
Forms, Getting Your Money's WorthForms, Getting Your Money's Worth
Forms, Getting Your Money's Worth
Alex Gaynor
 
Common Pitfalls Experienced in Java
Common Pitfalls Experienced in JavaCommon Pitfalls Experienced in Java
Common Pitfalls Experienced in Java
Exist
 
Html basics 11 form validation
Html basics 11 form validationHtml basics 11 form validation
Html basics 11 form validation
H K
 
Presentation technico-commercial-ruby-on-rails
Presentation technico-commercial-ruby-on-railsPresentation technico-commercial-ruby-on-rails
Presentation technico-commercial-ruby-on-rails
Novelys
 
Xml operations in odoo
Xml operations in odooXml operations in odoo
Xml operations in odoo
Celine George
 
What's New in newforms-admin
What's New in newforms-adminWhat's New in newforms-admin
What's New in newforms-admin
brosner
 
Working With The Symfony Admin Generator
Working With The Symfony Admin GeneratorWorking With The Symfony Admin Generator
Working With The Symfony Admin Generator
John Cleveley
 
The Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contribThe Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contrib
Tzu-ping Chung
 
Documentation For Tab Setup
Documentation For Tab SetupDocumentation For Tab Setup
Documentation For Tab Setup
vkeeton
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
Knoldus Inc.
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
Mohamed Mosaad
 
Repensando o Desenvolvimento Web com Ruby on Rails
Repensando o Desenvolvimento Web com Ruby on RailsRepensando o Desenvolvimento Web com Ruby on Rails
Repensando o Desenvolvimento Web com Ruby on Rails
Dante Regis
 
Django Admin (Python meeutp)
Django Admin (Python meeutp)Django Admin (Python meeutp)
Django Admin (Python meeutp)
Ines Jelovac
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
Mohit Jain
 
ALPHA Script - XML Model
ALPHA Script - XML ModelALPHA Script - XML Model
ALPHA Script - XML Model
PROBOTEK
 

Viewers also liked (7)

Dp carrier en
Dp carrier enDp carrier en
Dp carrier en
CompaniaDekartSRL
 
W make107
W make107W make107
W make107
Greg in SD
 
SWOT ppt
SWOT pptSWOT ppt
SWOT ppt
Vishnu Singh
 
SA02 - User and Password Management Techniques
SA02 - User and Password Management Techniques SA02 - User and Password Management Techniques
SA02 - User and Password Management Techniques
Maintenance Connection
 
2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL
Hung-yu Lin
 
Hitachi ID Password Manager: Enrollment, password reset and password synchron...
Hitachi ID Password Manager: Enrollment, password reset and password synchron...Hitachi ID Password Manager: Enrollment, password reset and password synchron...
Hitachi ID Password Manager: Enrollment, password reset and password synchron...
Hitachi ID Systems, Inc.
 
Django Best Practices
Django Best PracticesDjango Best Practices
Django Best Practices
Abdullah Çetin ÇAVDAR
 
SA02 - User and Password Management Techniques
SA02 - User and Password Management Techniques SA02 - User and Password Management Techniques
SA02 - User and Password Management Techniques
Maintenance Connection
 
2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL
Hung-yu Lin
 
Hitachi ID Password Manager: Enrollment, password reset and password synchron...
Hitachi ID Password Manager: Enrollment, password reset and password synchron...Hitachi ID Password Manager: Enrollment, password reset and password synchron...
Hitachi ID Password Manager: Enrollment, password reset and password synchron...
Hitachi ID Systems, Inc.
 
Ad

Similar to Two scoopsofdjango ch16 dealing with the user model (20)

Python Expense Tracker Project with Source Code.pdf
Python Expense Tracker Project with Source Code.pdfPython Expense Tracker Project with Source Code.pdf
Python Expense Tracker Project with Source Code.pdf
abhishekdf3
 
Cucumber Basics.pdf
Cucumber Basics.pdfCucumber Basics.pdf
Cucumber Basics.pdf
Mithilesh Singh
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
Ksd Che
 
Tips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxTips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptx
Agusto Sipahutar
 
Cis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry universityCis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry university
lhkslkdh89009
 
Connecting your Python App to OpenERP through OOOP
Connecting your Python App to OpenERP through OOOPConnecting your Python App to OpenERP through OOOP
Connecting your Python App to OpenERP through OOOP
raimonesteve
 
Cis 407 i lab 6 of 7
Cis 407 i lab 6 of 7Cis 407 i lab 6 of 7
Cis 407 i lab 6 of 7
helpido9
 
Django best practices for logging and signals
Django best practices for logging and signals Django best practices for logging and signals
Django best practices for logging and signals
flywindy
 
Django tricks (2)
Django tricks (2)Django tricks (2)
Django tricks (2)
Carlos Hernando
 
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
Christopher Adams
 
DJango
DJangoDJango
DJango
Sunil OS
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
Jacob Kaplan-Moss
 
Django web framework
Django web frameworkDjango web framework
Django web framework
Abdenour Bouateli
 
Lab StepsSTEP 1 Login Form1. In order to do this lab, we need.docx
Lab StepsSTEP 1 Login Form1. In order to do this lab, we need.docxLab StepsSTEP 1 Login Form1. In order to do this lab, we need.docx
Lab StepsSTEP 1 Login Form1. In order to do this lab, we need.docx
smile790243
 
Writing automation tests with python selenium behave pageobjects
Writing automation tests with python selenium behave pageobjectsWriting automation tests with python selenium behave pageobjects
Writing automation tests with python selenium behave pageobjects
Leticia Rss
 
Django Good Practices
Django Good PracticesDjango Good Practices
Django Good Practices
Solution4Future
 
Dexterity in the Wild
Dexterity in the WildDexterity in the Wild
Dexterity in the Wild
David Glick
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Joaquim Rocha
 
How to add Many2Many fields in odoo website form.pptx
How to add Many2Many fields in odoo website form.pptxHow to add Many2Many fields in odoo website form.pptx
How to add Many2Many fields in odoo website form.pptx
Celine George
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
Simon Willison
 
Python Expense Tracker Project with Source Code.pdf
Python Expense Tracker Project with Source Code.pdfPython Expense Tracker Project with Source Code.pdf
Python Expense Tracker Project with Source Code.pdf
abhishekdf3
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
Ksd Che
 
Tips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxTips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptx
Agusto Sipahutar
 
Cis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry universityCis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry university
lhkslkdh89009
 
Connecting your Python App to OpenERP through OOOP
Connecting your Python App to OpenERP through OOOPConnecting your Python App to OpenERP through OOOP
Connecting your Python App to OpenERP through OOOP
raimonesteve
 
Cis 407 i lab 6 of 7
Cis 407 i lab 6 of 7Cis 407 i lab 6 of 7
Cis 407 i lab 6 of 7
helpido9
 
Django best practices for logging and signals
Django best practices for logging and signals Django best practices for logging and signals
Django best practices for logging and signals
flywindy
 
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
Christopher Adams
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
Jacob Kaplan-Moss
 
Lab StepsSTEP 1 Login Form1. In order to do this lab, we need.docx
Lab StepsSTEP 1 Login Form1. In order to do this lab, we need.docxLab StepsSTEP 1 Login Form1. In order to do this lab, we need.docx
Lab StepsSTEP 1 Login Form1. In order to do this lab, we need.docx
smile790243
 
Writing automation tests with python selenium behave pageobjects
Writing automation tests with python selenium behave pageobjectsWriting automation tests with python selenium behave pageobjects
Writing automation tests with python selenium behave pageobjects
Leticia Rss
 
Dexterity in the Wild
Dexterity in the WildDexterity in the Wild
Dexterity in the Wild
David Glick
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Joaquim Rocha
 
How to add Many2Many fields in odoo website form.pptx
How to add Many2Many fields in odoo website form.pptxHow to add Many2Many fields in odoo website form.pptx
How to add Many2Many fields in odoo website form.pptx
Celine George
 
Ad

Recently uploaded (20)

Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
CSUC - Consorci de Serveis Universitaris de Catalunya
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 

Two scoopsofdjango ch16 dealing with the user model

  • 1. Two Scoops of Django Chapter 16 - Dealing with the User Model Alfred
  • 2. When you check out your user model… or…
  • 3. How it authenticates… login Authentication Backends authenticate Model.User Model.UserManager pass User View you know, the best way is to trace the python source code. backends: contrib.auth.backends.py model: contrib.auth.models.py admin(user view): contrib.auth.admin.py • • •
  • 4. Basic From Django 1.5 onwards, the official preferred way to attach ForeignKey, OneToOneField, or ManyToManyField to User is as follows: from django.conf import settings from django.db import models ! class IceCreamStore(models.model): owner = models.OneToOneField(settings.AUTH_USER_MODEL) title = models.CharField(max_length=255)
  • 5. To customize your user table, there are 3 options...
  • 6. Warranty We suggest that you carefully try out option #1 below, as it should work with a minimum of effort. For Django 1.5-style custom User model definitions, we recommend option #2 and option #3 for new projects only. ! This is is because custom User model definitions for option #2 and option #3 adds new User tables to the database that will not have the existing project data. Unless project-specific steps are taken to address matters, migration means ORM connections to related objects will be lost.
  • 7. Option 1 - Link back You continue to use User (called preferably via django.contrib.auth.get user model()) and keep your related fields in a separate model (e.g. Profile). from django.conf import settings from django.db import models class UserProfile(models.Model): # If you do this you need to either have a post_save signal or # redirect to a profile_edit view on initial login. user = models.OneToOneField(settings.AUTH_USER_MODEL) favorite_ice_cream = models.CharField(max_length=30)
  • 8. Option 2 AbstractUser Choose this option if you like Django’s User model fields the way they are, but need extra fields !from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ ! class KarmaUser(AbstractUser): karma = models.PositiveIntegerField(_("karma"), default=0, blank=True) #Setting.py AUTH_USER_MODEL = "profile.KarmaUser"
  • 9. Option 3 - Subclass AbstractBaseUser AbstractBaseUser is the bare-bones option with only 3 fields: password, last login, and is active. ! Let’s try it out with a custom User model for the Two Scoops project. Here are our requirements: We need an email address. We need to handle permissions per the traditional django.contrib.auth.models use of PermissionsMixin; providing standard behavior for the Django admin. We don’t need the first or last name of a user. We need to know their favorite ice cream topping. • • • •
  • 10. Option 3 - cont.(1) 1. Start from model. 2. Model.UserManager create User -> override it to create TwoScoopsUser 3. We need TwoScoopsUser! class TwoScoopsUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, db_index=True, ) favorite_topping = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) ! ! objects = TwoScoopsUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['favorite_topping']
  • 11. Option 3 - cont.(2) Implement usage functions… def get_full_name(self): return self.email ! def get_short_name(self): return self.email ! def __unicode__(self): return self.email ! def has_perm(self, perm, obj=None): return True ! def has_module_perms(self, app_label): return True
  • 12. Option 3 - cont. (3) Let’s write Model.UserManager to create TwoScoopsUser class TwoScoopsUserManager(BaseUserManager): def create_user(self, email, favorite_topping, password=None): """ Creates and saves a User with the given email, date of birth and password. """ ##Skip… user = self.model( email=TwoScoopsUserManager.normalize_email(email), favorite_topping=favorite_topping, ) ! user.set_password(password) user.save(using=self._db) return user
  • 13. Option 3 - cont. (4) Let’s write Model.UserManager to create TwoScoopsUser ! def create_superuser(self, email, favorite_topping, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user(email, password=password, favorite_topping=favorite_topping ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user
  • 14. Option 3 - Let Admin show your data. Basically, override contrib.auth.admin … class TwoScoopsUserAdmin(UserAdmin): # The forms to add and change user instances form = TwoScoopsUserChangeForm add_form = TwoScoopsUserCreationForm ! ! # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ("email", "is_staff", "favorite_topping") list_filter = ("is_staff", "is_superuser", "is_active", "groups") search_fields = ("email", "favorite_topping") ordering = ("email",) filter_horizontal = ("groups", "user_permissions",) fieldsets = ( (None, {"fields": ("email", "password")}), ("Personal info", {"fields": ("favorite_topping",)}), ("Permissions", {"fields": ("is_active", "is_staff", "is_superuser", "groups", "user_permissions")}), ("Important dates", {"fields": ("last_login",)}), ) add_fieldsets = ((None, { "classes": ("wide",), "fields": ("email", "favorite_topping", "password1", "password2")}), )
  • 15. Option 3 - Let Admin show your data. (2) Implement your forms class TwoScoopsUserCreationForm(UserCreationForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) #favorite_topping = forms.CharField( label='Faborate topping', widget=forms.TextInput) ! class Meta: model = TwoScoopsUser fields = ('email', 'favorite_topping') class TwoScoopsUserChangeForm(UserChangeForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ password = ReadOnlyPasswordHashField() ! class Meta: model = TwoScoopsUser fields = ["email", "password", "favorite_topping", "is_active", "is_staff", "is_superuser", "groups", "user_permissions", "last_login"]
  翻译: