SlideShare uma empresa Scribd logo
1 de 17
Baixar para ler offline
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"]
Thanks

Mais conteúdo relacionado

Mais procurados

Forms, Getting Your Money's Worth
Forms, Getting Your Money's WorthForms, Getting Your Money's Worth
Forms, Getting Your Money's WorthAlex Gaynor
 
Common Pitfalls Experienced in Java
Common Pitfalls Experienced in JavaCommon Pitfalls Experienced in Java
Common Pitfalls Experienced in JavaExist
 
Html basics 11 form validation
Html basics 11 form validationHtml basics 11 form validation
Html basics 11 form validationH K
 
Presentation technico-commercial-ruby-on-rails
Presentation technico-commercial-ruby-on-railsPresentation technico-commercial-ruby-on-rails
Presentation technico-commercial-ruby-on-railsNovelys
 
Xml operations in odoo
Xml operations in odooXml operations in odoo
Xml operations in odooCeline George
 
What's New in newforms-admin
What's New in newforms-adminWhat's New in newforms-admin
What's New in newforms-adminbrosner
 
Working With The Symfony Admin Generator
Working With The Symfony Admin GeneratorWorking With The Symfony Admin Generator
Working With The Symfony Admin GeneratorJohn 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.contribTzu-ping Chung
 
Documentation For Tab Setup
Documentation For Tab SetupDocumentation For Tab Setup
Documentation For Tab Setupvkeeton
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysqlKnoldus 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 CairoMohamed 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 RailsDante 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 ModelPROBOTEK
 

Mais procurados (20)

Forms, Getting Your Money's Worth
Forms, Getting Your Money's WorthForms, Getting Your Money's Worth
Forms, Getting Your Money's Worth
 
Common Pitfalls Experienced in Java
Common Pitfalls Experienced in JavaCommon Pitfalls Experienced in Java
Common Pitfalls Experienced in Java
 
Validation
ValidationValidation
Validation
 
Jsf lab
Jsf labJsf lab
Jsf lab
 
Html basics 11 form validation
Html basics 11 form validationHtml basics 11 form validation
Html basics 11 form validation
 
Presentation technico-commercial-ruby-on-rails
Presentation technico-commercial-ruby-on-railsPresentation technico-commercial-ruby-on-rails
Presentation technico-commercial-ruby-on-rails
 
Xml operations in odoo
Xml operations in odooXml operations in odoo
Xml operations in odoo
 
What's New in newforms-admin
What's New in newforms-adminWhat's New in newforms-admin
What's New in newforms-admin
 
Working With The Symfony Admin Generator
Working With The Symfony Admin GeneratorWorking With The Symfony Admin Generator
Working With The Symfony Admin Generator
 
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
 
Documentation For Tab Setup
Documentation For Tab SetupDocumentation For Tab Setup
Documentation For Tab Setup
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
 
HTML Form Part 1
HTML Form Part 1HTML Form Part 1
HTML Form Part 1
 
Specs2
Specs2Specs2
Specs2
 
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
 
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
 
Django Admin (Python meeutp)
Django Admin (Python meeutp)Django Admin (Python meeutp)
Django Admin (Python meeutp)
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
 
Django Bogotá. CBV
Django Bogotá. CBVDjango Bogotá. CBV
Django Bogotá. CBV
 
ALPHA Script - XML Model
ALPHA Script - XML ModelALPHA Script - XML Model
ALPHA Script - XML Model
 

Destaque

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 MySQLHung-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.
 

Destaque (7)

Dp carrier en
Dp carrier enDp carrier en
Dp carrier en
 
W make107
W make107W make107
W make107
 
SWOT ppt
SWOT pptSWOT ppt
SWOT ppt
 
SA02 - User and Password Management Techniques
SA02 - User and Password Management Techniques SA02 - User and Password Management Techniques
SA02 - User and Password Management Techniques
 
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
 
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...
 
Django Best Practices
Django Best PracticesDjango Best Practices
Django Best Practices
 

Semelhante a Two scoopsofdjango ch16 dealing with the user model

Django tutorial
Django tutorialDjango tutorial
Django tutorialKsd 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.pptxAgusto 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 universitylhkslkdh89009
 
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 OOOPraimonesteve
 
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 7helpido9
 
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
 
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.docxsmile790243
 
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 pageobjectsLeticia Rss
 
Dexterity in the Wild
Dexterity in the WildDexterity in the Wild
Dexterity in the WildDavid Glick
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
Customizing the Django Admin
Customizing the Django AdminCustomizing the Django Admin
Customizing the Django AdminLincoln Loop
 
TangoWithDjango - ch8
TangoWithDjango - ch8TangoWithDjango - ch8
TangoWithDjango - ch8Asika Kuo
 
Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009Ferenc Szalai
 

Semelhante a Two scoopsofdjango ch16 dealing with the user model (20)

Cucumber Basics.pdf
Cucumber Basics.pdfCucumber Basics.pdf
Cucumber Basics.pdf
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
 
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
 
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
 
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
 
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
 
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
 
Django tricks (2)
Django tricks (2)Django tricks (2)
Django tricks (2)
 
DJango
DJangoDJango
DJango
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
 
Django web framework
Django web frameworkDjango web framework
Django web framework
 
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
 
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
 
Django Good Practices
Django Good PracticesDjango Good Practices
Django Good Practices
 
Dexterity in the Wild
Dexterity in the WildDexterity in the Wild
Dexterity in the Wild
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
Customizing the Django Admin
Customizing the Django AdminCustomizing the Django Admin
Customizing the Django Admin
 
TangoWithDjango - ch8
TangoWithDjango - ch8TangoWithDjango - ch8
TangoWithDjango - ch8
 
Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009
 

Último

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 

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"]
  • 16.