Django Authentication register API - django

I am trying to register users in django auth module through an API call but the users are getting registered without the password being hashed which, I suspect, is making my authentication fail. Registering the users through the admin form is hashing the password and therefore working.
I developed my own User model by extending AbstractBaseUser and also created a UserManager extending BaseUserManager and defining the create_user and create_superuser method. I developed a simple serializer for it.
I read somewhere that the password can only be hashed if I developed the Admin form as well and so I did it. In this form, I followed django documentation and developed clean_password and save functions. I also registered these forms on the app admin.py.
Lastly, I created the APIView to the POST requests where I send the registration json and use the serializer do validate and save.
model
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError('The given email must be set')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **extra_fields):
user = self.create_user(email,
password=password,
**extra_fields)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(max_length=40, unique=True)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
photo_path = models.CharField(max_length=30, blank=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def save(self, *args, **kwargs):
super(User, self).save(*args, **kwargs)
return self
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.is_admin
serializer
class UserSerializer(serializers.ModelSerializer):
class Meta(object):
model = User
fields = ('id', 'email', 'first_name', 'last_name', 'password')
extra_kwargs = {'password': {'write_only': True}}
forms
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email', 'photo_path')
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
class Meta:
model = User
fields = ('email', 'photo_path', 'password')
def clean_password(self):
return self.initial["password"]
admin.py
class UserAdmin(BaseUserAdmin):
form = UserChangeForm
add_form = UserCreationForm
list_display = ('email', 'first_name', 'is_staff')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('first_name',)}),
('Permissions', {'fields': ('is_admin',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
admin.site.register(User, UserAdmin)
view post
class CreateUserAPIView(APIView):
permission_classes = (AllowAny,)
def post(self, request):
user = request.data
serializer = UserSerializer(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
I expected to get a user in the DB with a hashed password, like when I create a user in the admin panel. but I get a user created with a plain text password.

What I would do, is the following in your serializer. Notice the set_password. That way you make sure it is hashed
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = models.User
fields = ('username', 'password', 'email')
def create(self, validated_data):
user = super(UserSerializer, self).create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user

If you are using md5 for hashing then you can use the hashlib module and hash the password before saving in create_superuser
form hashlib import md5
def create_superuser(self, email, password, **extra_fields):
user = self.create_user(email,password=md5(password),**extra_fields)
user.is_admin = True
user.save(using=self._db)
return user

Sorry for the quick auto-response but I found out that the view post code was actually not executing my model create_user code. I don't know what was connecting the .save() method of the serializer to the authentication system but it was still creating the users. I will leave this question open so someone can maybe explain what was happening. To make it work i did the following changes:
class CreateUserAPIView(APIView):
permission_classes = (AllowAny,)
def post(self, request):
user = User.objects.create_user(request.data['email'], request.data['password']);
return Response(user, status=status.HTTP_201_CREATED)

Related

Custom Register Form with Django Rest Auth - Error: save() takes 1 positional argument but 2 were given

I want to create a custom Signup form with Django Rest Auth and Django Allauth but I'm getting an error save() takes 1 positional argument but 2 were given
I know that this error is related to the function def save(self, request) provided by Django Rest Auth, but I have no clue how I can change it.
What should I do to make it work?
Bellow is the respective code for my user Model and Serializer:
# Models.py
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a new user"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **extra_fields):
"""Creates and saves a new super user"""
user = self.create_user(email, password, **extra_fields)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""Custom user model that supports using email instead of username"""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
age = models.PositiveIntegerField(null=True, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name', 'age']
def __str__(self):
return self.email
# serializers.py
class UserSerializer(serializers.ModelSerializer):
"""Serializer for the users object"""
class Meta:
model = get_user_model()
fields = ('email', 'password', 'name', 'age')
extra_kwargs = {'password': {'write_only': True, 'min_length': 5}}
def create(self, validated_data):
"""Create a new user with encrypted password and return it"""
return get_user_model().objects.create_user(**validated_data)
def update(self, instance, validated_data):
"""Update a user, setting the password correctly and return it"""
password = validated_data.pop('password', None)
user = super().update(instance, **validated_data)
if password:
user.set_password(password)
user.save()
return user
def save(self, request):
# I would say that I need to change the default function
# settings. py
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER': 'user.serializers.UserSerializer'
}
In order to get this fixed I just add the following to my serializer:
class UserSerializer(serializers.ModelSerializer):
"""Serializer for the users object"""
class Meta:
model = get_user_model()
fields = ('email', 'password', 'name', 'age')
extra_kwargs = {'password': {'write_only': True, 'min_length': 5}}
def create(self, validated_data):
"""Create a new user with encrypted password and return it"""
return get_user_model().objects.create_user(**validated_data)
def update(self, instance, validated_data):
"""Update a user, setting the password correctly and return it"""
password = validated_data.pop('password', None)
user = super().update(instance, **validated_data)
if password:
user.set_password(password)
user.save()
return user
def get_cleaned_data(self):
return {
'password': self.validated_data.get('password', ''),
'email': self.validated_data.get('email', ''),
'name': self.validated_data.get('name', ''),
'age': self.validated_data.get('age', ''),
}
def save(self, request):
self.cleaned_data = self.get_cleaned_data()
user = get_user_model().objects.create_user(**self.cleaned_data)
return user

django.core.exceptions.FieldError: Unknown field(s) specified by user

I'm using Django 2.0
I have extended AbstractBaseUser model to create a custom User model.
In my accounts/models.py
class UserManager(BaseUserManager):
def create_user(self, email, password=None, is_staff=False, is_admin=False, is_active=False):
if not email:
raise ValueError('User must have an email address')
if not password:
raise ValueError('User must have a password')
user = self.model(
email=self.normalize_email(email)
)
user.is_staff = is_staff
user.is_admin = is_admin
user.is_active = is_active
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, password=None):
return self.create_user(
email,
password=password,
is_staff=True,
is_active=True
)
def create_superuser(self, email, password=None):
return self.create_user(
email,
password=password,
is_staff=True,
is_admin=True,
is_active=True
)
class User(AbstractBaseUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email = models.EmailField(max_length=250, blank=False, unique=True)
first_name = models.CharField(max_length=150, blank=True)
last_name = models.CharField(max_length=150, blank=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
groups = models.ManyToManyField(Group, blank=True)
last_login = models.DateTimeField(auto_now=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
objects = UserManager()
#property
def is_staff(self):
return self.is_staff
#property
def is_active(self):
return self.is_active
#property
def is_superuser(self):
return self.is_admin
def __str__(self):
if self.first_name is not None:
return self.get_full_name()
return self.email
def get_full_name(self):
if self.last_name is not None:
return self.first_name + ' ' + self.last_name
return self.get_short_name()
def get_short_name(self):
return self.first_name
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
and to use this User model for admin as well. I have added below code to
accounts/admin.py as given in example
from accounts.models import User
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.contrib.auth.models import Group
class UserCreationForm(forms.ModelForm):
"""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)
class Meta:
model = User
fields = ('email', 'first_name', 'last_name')
def clean_password2(self):
# 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:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""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 = User
fields = ('email', 'password', 'first_name', 'last_name', 'is_active', 'is_admin', 'is_staff')
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 UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# 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', 'first_name', 'last_name', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('first_name', 'last_name',)}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'first_name', 'last_name', 'password1', 'password2')}
),
)
search_fields = ('email', 'first_name', 'last_name',)
ordering = ('email', 'first_name', 'last_name',)
filter_horizontal = ()
# Now register the new UserAdmin...
admin.site.register(User, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
But when I run
python manage.py makemigrations
It gives error as
File "/Users/anuj/code/PyCharm/notepad/src/accounts/admin.py", line 37, in <module>
class UserChangeForm(forms.ModelForm):
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (is_staff, is_active) specified for User
removing is_staff and is_active from UserChangeForm works fine. I have even fields added to model.
Since you are using a custom user model for authentication you must say so in your settings
In settings.py write:
AUTH_USER_MODEL = 'accounts.User'
Source

Edit the admin panel using Custom user authentication

Using the documentation I am trying to create a custom authentication model in order to be able to use only Email and password to authenticate a user.
Despite I manage to do it, I am having trouble to edit the Admin panel and in particular the Edit form could you please help me to add the possible editable field.
my code is :
admin.py:
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from registration.models import MyUser
class UserCreationForm(forms.ModelForm):
"""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)
class Meta:
model = MyUser
fields = ('email','is_active','is_hr','is_candidate','is_employee','company','first_name','last_name')
def clean_password2(self):
# 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:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""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 = MyUser
fields = ('email', 'password', 'is_active', 'is_admin','is_hr','is_candidate','is_employee','company','first_name','last_name')
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 UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# 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_admin','is_active', 'is_admin','is_hr','is_candidate','is_employee','company','first_name','last_name')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# Now register the new UserAdmin...
admin.site.register(MyUser, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
model.py:
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class MyUserManager(BaseUserManager):
def create_Euser(self, email):
"""
Creates and saves a User with the given email,
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email)
)
user.save(using=self._db)
return user
def create_user(self, email, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email)
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
email,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name= models.CharField(max_length=150, default='')
last_name= models.CharField(max_length=150, default='')
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_hr = models.BooleanField(default=False)
is_candidate = models.BooleanField(default=False)
is_employee = models.BooleanField(default=False)
company = models.CharField(max_length=100, default='')
objects = MyUserManager()
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
def get_short_name(self):
# The user is identified by their email address
return self.email
#property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
You can add all you model fields.for that you should have to add field in fieldsets under UserAdmin.
change you fieldsets as below:
fieldsets = (
(None, {'fields': ('email', 'password','company','first_name','last_name')}),
('Permissions', {'fields': ('is_admin','is_active','is_hr','is_candidate','is_employee')}),
)
Above changes will add fields to django-admin.

django custom user model password is not being hashed

I have my own custom User model, and its own Manger too.
models:
class MyUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=35)
last_name = models.CharField(max_length=35)
username = models.CharField(max_length=70, unique=True)
date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
#property
def is_staff(self):
return self.is_admin
def get_full_name(self):
return ('%s %s') % (self.first_name, self.last_name)
def get_short_name(self):
return self.username
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'username', 'date_of_birth']
manager:
class MyUserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, username, date_of_birth, password=None, **kwargs):
if not email:
raise ValueError('User must have an email address')
user = self.model(
email=self.normalize_email(email),
first_name=first_name,
last_name=last_name,
username=username,
date_of_birth=date_of_birth,
**kwargs
)
user.set_password(self.cleaned_data["password"])
user.save(using=self._db)
return user
def create_superuser(self, email, first_name, last_name, username, date_of_birth, password, **kwargs):
user = self.create_user(
email,
first_name=first_name,
last_name=last_name,
username=username,
date_of_birth=date_of_birth,
password=password,
is_superuser=True,
**kwargs
)
user.is_admin = True
user.save(using=self._db)
return user
Everything works when creating a new user without any errors. But when I try to login I can't. So I checked the user's password to confirm and the password is displayed as plain text strongpassword, and when changed admin form to get the hashed password using ReadOnlyPasswordHashField I get an error inside the password field, even though I used set_password() for the Manger inside the create_user() function.
Invalid password format or unknown hashing algorithm
However, if I manually do set_password('strongpassword') for that user it is then hashed. Could you please help me solve this problem. Thank you.
It looks like you created a user in a way that does not use your manager's create_user method, for example through the Django admin.
If you create a custom user, you need to define a custom model form and model admin that handles the password properly.
Otherwise, passwords will not hashed when a user is created through the Django admin.
The example in docs for creating a custom users shows how to create the model form and model admin.
I know it's too late now, but I'll just post this for future reference.
If you're creating a new user by calling the save function on its serializer, you'll need to override the create function of the serializer as shown below, (which is pretty obvious, but I got stuck on it for a little bit....)
class SignUpView(views.APIView):
authentication_classes = ()
permission_classes = (permissions.AllowAny,)
def post(self, request, format=None):
serializer = UserSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(
min_length=6, write_only=True, required=True)
class Meta:
model = User
fields = (
'id', 'email', 'password', 'is_staff',
'is_active', 'date_joined')
def create(self, validated_data):
return User.objects.create_user(**validated_data)
Late answer but anyway, you need to make Custom User Model form too with explicit hashing.
Else just make form inheriting UserCreationForm like:
from .models import MyUser
from django.contrib.auth.forms import UserCreationForm
class UserForm(UserCreationForm):
class Meta:
model = User
fields = ['email']
Add this in your UserSerialzer.
Basically you have to override the create method in order to hash the password.
def create(self,validated_data):
user = User.objects.create(email = validated_data['email'])
user.set_password(validated_data['password'])
user.save()
return user

Can't get Django custom user model to work with admin

I created a custom user model (following this writeup), and I manage to get the signup and login to work. However, I'm having trouble logging into admin. Specifically, even after "successfully" created a superuser, I'm unable to login to the admin and got error message: "Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive."
For the sake of completeness, I'm attaching the following code. I know it's a lot but any suggestion would be helpful. Thanks!!
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email),
)
user.is_active = True
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(email=email, password=password)
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""
Custom user class.
"""
email = models.EmailField('email address', unique=True, db_index=True)
joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
custom backend in backends.py
from django.conf import settings
from django.contrib.auth.models import check_password
from account.models import User
class EmailAuthBackend(object):
"""
A custom authentication backend. Allows users to log in using their email address.
"""
def authenticate(self, email=None, password=None):
"""
Authentication method
"""
try:
user = User.objects.get(email=email)
if user.check_password(password):
return user
else:
print('Password not correct')
except User.DoesNotExist:
print('User does not exist')
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, ReadOnlyPasswordHashField
from .models import User as AuthUser
from django import forms
class CustomUserCreationForm(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)
class Meta(UserCreationForm.Meta):
model = AuthUser
fields = ('email',)
def clean_password2(self):
#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:
raise forms.ValidationError("Passwords do not match.")
return password2
def save(self, commit=True):
#Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class CustomUserChangeForm(UserChangeForm):
password = ReadOnlyPasswordHashField(label="password",
help_text="""Raw passwords are not stored, so there is no way to see this
user's password, but you can change the password using <a href=\"password/\">
this form</a>.""")
class Meta(UserChangeForm.Meta):
model = AuthUser
fields = ('email', 'password', 'is_active', 'is_superuser', 'user_permissions')
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 AuthUserAdmin(UserAdmin):
form = CustomUserChangeForm
add_form = CustomUserCreationForm
list_display = ('email', 'is_superuser')
list_filter = ('is_superuser',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Permissions', {'fields': ('is_active', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2', 'is_superuser')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ('groups', 'user_permissions',)
admin.site.register(AuthUser, AuthUserAdmin)
The attribute that controls access to the admin is is_staff, not is_admin.
If you wanted to keep your current field for whatever reason, you could define an is_staff() method and make it a property.
Upgrade your Django to 1.9 version. I had resolved this issue using:
$ pip install django==1.9b1