• Aucun résultat trouvé

Option 3: Subclass AbstractBaseUser

Dans le document Two Scoops of Django (Page 189-197)

WARNING: Third-Party Packages Should Not Be Defining the User Model

16.2.3 Option 3: Subclass AbstractBaseUser

.

E .

AUTH_USER_MODEL = "profiles.KarmaUser"

16.2.3 Option 3: Subclass AbstractBaseUser

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

Choose this option if:

ä You’re unhappy with the elds that theUsermodel provides by default, such asfirst name andlast name.

ä You prefer to subclass from an extremely bare-bones clean slate but want to take advantage of theAbstractBaseUsersane default approach to storing passwords.

..

WARNING: Third-Party Packages Should Not Be Defining the User Model

.

Unless the express purpose of the third-party package is to provide a newUsermodel, third-party packages should never use option #3 to add elds to the User model.

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

ä We need an email address.

ä We need to handle permissions per the traditionaldjango.contrib.auth.modelsuse of PermissionsMixin; providing standard behavior for the Django admin.

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

ä We need to know their favorite ice cream topping.

Looking over the Django 1.5 documentation on customizing the User model, we notice there is a full example (http://2scoops.co/1.5-customizing-user). It doesn’t do exactly what we want, but we can modify it. Speci cally:

ä We’ll need to addPermissionsMixinto our custom User model.

Chapter 16: Dealing With the User Model

ä We’ll need to implement a favorite toppings eld.

ä We’ll need to ensure that the admin.py fully supports our customUser model. Unlike the example in the documentation, we do want to track groups and permissions.

Let’s do it! We’ll call our new User model,TwoScoopsUser.

Before we start writing our newTwoScoopsUsermodel, we need to write a custom TwoScoop-sUserManager. is is generally required for customUsermodels as the auth system expects certain methods on the default manager, but the manager for the default user class expects elds we are not providing.

Creates and saves a User with the given email, favorite topping, and password.

"""

if not email:

msg = "Users must have an email address"

raise ValueError(msg)

if not favorite_topping:

msg = "Users must have a favorite topping"

raise ValueError(msg)

user = self.model(

email=TwoScoopsUserManager.normalize_email(email), favorite_topping=favorite_topping,

16.2: Custom User Fields for Projects Starting at Django 1.5

Creates and saves a superuser with the given email, favorite topping and password.

With ourTwoScoopsUserManagercomplete, we can write theTwoScoopsUserclass.

. .

E .

# profiles/models.py (after the TwoScoopsUserManager) class TwoScoopsUser(AbstractBaseUser, PermissionsMixin):

""" Inherits from both the AbstractBaseUser and PermissionMixin.

Chapter 16: Dealing With the User Model

# The user is identified by their email and

# favorite topping

return "%s prefers %s" % (self.email, self.favorite_topping)

def get_short_name(self):

# The user is identified by their email address return self.email

def __unicode__(self):

return self.email

Boom! ere’s nofirst nameorlast name, which is probably what you wanted if you’re choos-ing this option. e permissions are in place and most importantly, users have a favorite ice cream topping!

Like the rst option, don’t forget to set this in your settings:

. .

E .

# settings/base.py

AUTH_USER_MODEL = "profiles.TwoScoopsUser"

16.2: Custom User Fields for Projects Starting at Django 1.5 Uponsyncdb, this will create a newTwoScoopsUsertable and various other references. We ask that you try this on a new database rather than an existing one.

Once the table has been created, we can create a superuser locally via the shell:

python manage.py createsuperuser

With our new superuser account in hand, let’s create thepro les/admin.pyso we can see the results.

Again, we follow the lead of the example in the Django documentation. We modify it to include the permissions and favorite toppings elds. e results:

.

"""A form for creating new users. Includes all the required fields, plus a repeated password.

"""

# Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2")

if password1 and password2 and password1 != password2:

Chapter 16: Dealing With the User Model

. . msg = "Passwords don't match"

raise forms.ValidationError(msg) return password2

def save(self, commit=True):

# Save the provided password in hashed format user = super(TwoScoopsUserCreationForm,

""" 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

def clean_password(self):

# Regardless of what the user provides, return the

# initial value. This is done here, rather than on

# the field, because the field does not have access

# to the initial value

return self.initial["password"]

class TwoScoopsUserAdmin(UserAdmin):

# Set the add/modify forms

add_form = TwoScoopsUserCreationForm form = TwoScoopsUserChangeForm

# The fields to be used in displaying the User model.

# These override the definitions on the base UserAdmin

16.3: Summary

. .

# that reference specific fields on auth.User.

list_display = ("email", "is_staff", "favorite_topping") list_filter = ("is_staff", "is_superuser",

# Register the new TwoScoopsUserAdmin

admin.site.register(TwoScoopsUser, TwoScoopsUserAdmin)

Now if you go to your admin home and login, you’ll be able to create and modify theTwoScoopsUser model records.

16.3 Summary

e newUsermodel makes this an exciting time to be involved in Django. We are getting to par-ticipate in a major infrastructure change with wide-ranging implications. We are the ones who get

Chapter 16: Dealing With the User Model to pioneer the best practices.

In this chapter we covered the new method to nd theUsermodel and de ne our own custom ones.

Depending on the needs of a project, they can either continue with the current way of doing things or customize the actual user model.

e next chapter is a dive into the world of third-party packages.

17 | Django's Secret Sauce:

Dans le document Two Scoops of Django (Page 189-197)

Documents relatifs